1 using System.IO; 2 using System.Security.Cryptography; 3 using System.Text; 4 5 6 /// <summary> 7 /// 计算文件的MD5码 8 /// </summary> 9 public class ComputeFileMD5 10 { 11 #region 私有变量及属性 12 13 /// <summary> 14 /// MD5对象 15 /// </summary> 16 private MD5 md5Obj; 17 /// <summary> 18 /// MD5属性 19 /// </summary> 20 private MD5 MD5Obj 21 { 22 get { return md5Obj ?? (md5Obj = MD5.Create()); } 23 } 24 25 #endregion 26 27 #region 私有方法 28 29 /// <summary> 30 /// 计算一个字节数组的MD5码 31 /// </summary> 32 /// <param name="bytes">参与计算的字节数组</param> 33 /// <returns>结算获得的MD5码</returns> 34 private string ComputeHash(byte[] bytes) 35 { 36 if (null == bytes || bytes.Length <= 0) 37 return ""; 38 byte[] hash = MD5Obj.ComputeHash(bytes); 39 StringBuilder sb = new StringBuilder(); 40 foreach (var data in hash) 41 { 42 sb.Append(data.ToString("x2")); 43 } 44 return sb.ToString(); 45 } 46 47 /// <summary> 48 /// 将文件读取为字节数组 49 /// </summary> 50 /// <param name="filePath">文件路径</param> 51 /// <returns>字节数组读取结果</returns> 52 private byte[] ReadBytesFromFile(string filePath) 53 { 54 if (string.IsNullOrEmpty(filePath)) 55 return null; 56 57 return File.ReadAllBytes(filePath); 58 } 59 60 #endregion 61 62 63 #region 公有方法 64 65 /// <summary> 66 /// 计算文件的MD5码 67 /// </summary> 68 /// <param name="filePath">文件路径</param> 69 /// <returns>文件计算获得的MD5码</returns> 70 public string ComputeMD5(string filePath) 71 { 72 if (!File.Exists(filePath)) 73 return ""; 74 byte[] bytes = ReadBytesFromFile(filePath); 75 return null != bytes ? ComputeHash(bytes) : null; 76 } 77 78 #endregion 79 }
测试用例:
1 using System; 2 3 namespace myMethod 4 { 5 class lgs 6 { 7 static void Main() 8 { 9 ComputeFileMD5 tool = new ComputeFileMD5(); 10 string path = @"D:DOTween Pro 0.9.690.unitypackage"; 11 string md5 = tool.ComputeMD5(path); 12 Console.WriteLine(md5); 13 Console.ReadKey(); 14 } 15 } 16 }
输出结果: