首页 > 代码库 > C# MD5校验
C# MD5校验
1.方法1
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); } }
2.方法2
//计算文件的MD5码
private string getMD5Hash(string pathName)
{
string strResult = "";
string strHashData =http://www.mamicode.com/ "";
byte[] arrbytHashValue;
System.IO.FileStream oFileStream = null;
System.Security.Cryptography.MD5CryptoServiceProvider oMD5Hasher = new System.Security.Cryptography.MD5CryptoServiceProvider();
try
{
oFileStream = new System.IO.FileStream(pathName, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.ReadWrite));
arrbytHashValue = http://www.mamicode.com/oMD5Hasher.ComputeHash(oFileStream);//计算指定Stream 对象的哈希值
oFileStream.Close();
//由以连字符分隔的十六进制对构成的String,其中每一对表示value 中对应的元素;例如“F-2C-4A”
strHashData = http://www.mamicode.com/System.BitConverter.ToString(arrbytHashValue);
//替换-
strHashData = http://www.mamicode.com/strHashData.Replace("-", "");
strResult = strHashData;
}
catch (System.Exception ex)
{
MessageBox.Show(ex.Message);
}
return strResult;
}
3.比较。
方法1和方法2虽然都能计算文件的MD5,但是方法2在针对大文件时,更快,所以更好。
C# MD5校验