MD5Helper.cs 963 B

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. using System.IO;
  2. using System.Security.Cryptography;
  3. using System.Text;
  4. namespace ET
  5. {
  6. public static class MD5Helper
  7. {
  8. /// <summary>
  9. /// 获取文件md5
  10. /// </summary>
  11. /// <param name="filePath"></param>
  12. /// <returns></returns>
  13. public static string FileMD5(string filePath)
  14. {
  15. byte[] retVal;
  16. using (FileStream file = new FileStream(filePath, FileMode.Open))
  17. {
  18. MD5 md5 = MD5.Create();
  19. retVal = md5.ComputeHash(file);
  20. }
  21. return retVal.ToHex("x2");
  22. }
  23. /// <summary>
  24. /// 获取字符串md5
  25. /// </summary>
  26. /// <param name="str"></param>
  27. /// <returns></returns>
  28. public static string StringMD5(string str)
  29. {
  30. byte[] retVal = Encoding.GetEncoding("UTF-8").GetBytes(str);
  31. byte[] hashValue = MD5.Create().ComputeHash(retVal);
  32. StringBuilder tmp = new StringBuilder();
  33. foreach (byte i in hashValue)
  34. {
  35. tmp.Append(i.ToString("x2"));
  36. }
  37. return tmp.ToString();
  38. }
  39. }
  40. }