C# 获取 文件的哈希值(MD5、SHA),验证相同文件。
一获取文件的MD5:
MD5是一种常见的加密方式,相对比较稳定,同时也是校验文件的一种方式,HZ下面分享net中获取文件md5值的方法,
private static string GetMD5HashFromFile(string fileName) { try { FileStream file = new FileStream(fileName, FileMode.Open); System.Security.Cryptography.MD5 md5 = new System.Security.Cryptography.MD5CryptoServiceProvider(); byte[] retVal = md5.ComputeHash(file); file.Close(); StringBuilder sb = new StringBuilder(); for (int i = 0; i < retVal.Length; i++) { sb.Append(retVal[i].ToString(“x2″)); } return sb.ToString(); } catch (Exception ex) { throw new Exception(“GetMD5HashFromFile() fail,error:” + ex.Message); } }
二:获取文件的SHA
public static string GetSHA1(string s) { try { FileStream file = new FileStream(s, FileMode.Open); SHA1 sha1 = new SHA1CryptoServiceProvider(); byte[] retval = sha1.ComputeHash(file); file.Close(); StringBuilder sc = new StringBuilder(); for (int i = 0; i < retval.Length; i++) { sc.Append(retval[i].ToString("x2")); } Console.WriteLine("文件SHA1:{0}", sc); return sc.ToString(); } catch (Exception ex) { Console.WriteLine(ex.Message); return string.Empty; } }