标签:比较 null catch com 文件 builder omd 大文件 data
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 = "";
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 = oMD5Hasher.ComputeHash(oFileStream);//计算指定Stream 对象的哈希值
oFileStream.Close();
//由以连字符分隔的十六进制对构成的String,其中每一对表示value 中对应的元素;例如“F-2C-4A”
strHashData = System.BitConverter.ToString(arrbytHashValue);
//替换-
strHashData = strHashData.Replace("-", "");
strResult = strHashData;
}
catch (System.Exception ex)
{
MessageBox.Show(ex.Message);
}
return strResult;
}
3.比较。
方法1和方法2虽然都能计算文件的MD5,但是方法2在针对大文件时,更快,所以更好。
标签:比较 null catch com 文件 builder omd 大文件 data
原文地址:http://www.cnblogs.com/Cpart/p/7002980.html