FileCodeTool.cs 3.1 KB

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