FileCodeHelper.cs 2.7 KB

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