C# 获取文件MD5值的方法

2018-06-22 14:50:40 浏览数 (1)

可用于对比文件是否相同

代码语言:javascript复制
 1 /// <summary>
 2         /// 获取文件MD5值
 3         /// </summary>
 4         /// <param name="fileName">文件绝对路径</param>
 5         /// <returns>MD5值</returns>
 6         public static string GetMD5HashFromFile(string fileName)
 7         {
 8             try
 9             {
10                 FileStream file = new FileStream(fileName, FileMode.Open);
11                 System.Security.Cryptography.MD5 md5 = new System.Security.Cryptography.MD5CryptoServiceProvider();
12                 byte[] retVal = md5.ComputeHash(file);
13                 file.Close();
14 
15                 StringBuilder sb = new StringBuilder();
16                 for (int i = 0; i < retVal.Length; i  )
17                 {
18                     sb.Append(retVal[i].ToString("x2"));
19                 }
20                 return sb.ToString();
21             }
22             catch (Exception ex)
23             {
24                 throw new Exception("GetMD5HashFromFile() fail,error:"   ex.Message);
25             }
26         }

0 人点赞