Loading

C# 获取文件MD5值的方法

可用于对比文件是否相同

 

 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         }

 

posted @ 2016-11-22 17:30  晓晨Master  阅读(18746)  评论(0编辑  收藏  举报