FileCodeTool.cs 3.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. //************************************************************************
  2. // author: yuzhengyang
  3. // date: 2017.3.29 - 2017.6.10
  4. // desc: 获取文件特征码
  5. // Copyright (c) yuzhengyang. All rights reserved.
  6. //************************************************************************
  7. using System;
  8. namespace Azylee.Core.IOUtils.FileUtils
  9. {
  10. /// <summary>
  11. /// 获取文件特征码(MD5,SHA1)
  12. /// </summary>
  13. public class FileCodeTool
  14. {
  15. /// <summary>
  16. /// 计算文件的 MD5 值
  17. /// </summary>
  18. /// <param name="fileName">要计算 MD5 值的文件名和路径</param>
  19. /// <returns>MD5 值16进制字符串</returns>
  20. public string GetMD5(string fileName)
  21. {
  22. return HashFile(fileName, "md5");
  23. }
  24. /// <summary>
  25. /// 计算文件的 sha1 值
  26. /// </summary>
  27. /// <param name="fileName">要计算 sha1 值的文件名和路径</param>
  28. /// <returns>sha1 值16进制字符串</returns>
  29. public string GetSHA1(string fileName)
  30. {
  31. return HashFile(fileName, "sha1");
  32. }
  33. /// <summary>
  34. /// 计算文件的哈希值
  35. /// </summary>
  36. /// <param name="fileName">要计算哈希值的文件名和路径</param>
  37. /// <param name="algName">算法:sha1,md5</param>
  38. /// <returns>哈希值16进制字符串</returns>
  39. private string HashFile(string fileName, string algName)
  40. {
  41. if (!System.IO.File.Exists(fileName))
  42. return string.Empty;
  43. System.IO.FileStream fs = new System.IO.FileStream(fileName, System.IO.FileMode.Open, System.IO.FileAccess.Read);
  44. byte[] hashBytes = HashData(fs, algName);
  45. fs.Close();
  46. return ByteArrayToHexString(hashBytes);
  47. }
  48. /// <summary>
  49. /// 计算哈希值
  50. /// </summary>
  51. /// <param name="stream">要计算哈希值的 Stream</param>
  52. /// <param name="algName">算法:sha1,md5</param>
  53. /// <returns>哈希值字节数组</returns>
  54. private byte[] HashData(System.IO.Stream stream, string algName)
  55. {
  56. System.Security.Cryptography.HashAlgorithm algorithm;
  57. if (algName == null)
  58. {
  59. throw new ArgumentNullException("algName 不能为 null");
  60. }
  61. if (string.Compare(algName, "sha1", true) == 0)
  62. {
  63. algorithm = System.Security.Cryptography.SHA1.Create();
  64. }
  65. else
  66. {
  67. if (string.Compare(algName, "md5", true) != 0)
  68. {
  69. throw new Exception("algName 只能使用 sha1 或 md5");
  70. }
  71. algorithm = System.Security.Cryptography.MD5.Create();
  72. }
  73. return algorithm.ComputeHash(stream);
  74. }
  75. /// <summary>
  76. /// 字节数组转换为16进制表示的字符串
  77. /// </summary>
  78. private string ByteArrayToHexString(byte[] buf)
  79. {
  80. return BitConverter.ToString(buf).Replace("-", "");
  81. }
  82. }
  83. }