FileCodeTool.cs 2.9 KB

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