FileCode.cs 2.8 KB

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