C#如何高效的计算文件的MD5值?
网上搜了一片,目前找到最快的是。
public static string getMD5ByHashAlgorithm(string path)
{
if (!File.Exists(path))
throw new ArgumentException(string.Format("<{0}>, 不存在", path));
int bufferSize = 1024 * 16;//自定义缓冲区大小16K
byte[] buffer = new byte[bufferSize];
Stream inputStream = File.Open(path, FileMode.Open, FileAccess.Read, FileShare.Read);
HashAlgorithm hashAlgorithm = new MD5CryptoServiceProvider();
int readLength = 0;//每次读取长度
var output = new byte[bufferSize];
while ((readLength = inputStream.Read(buffer, 0, buffer.Length)) > 0)
{
//计算MD5
hashAlgorithm.TransformBlock(buffer, 0, readLength, output, 0);
}
//完成最后计算,必须调用(由于上一部循环已经完成所有运算,所以调用此方法时后面的两个参数都为0)
hashAlgorithm.TransformFinalBlock(buffer, 0, 0);
string md5 = BitConverter.ToString(hashAlgorithm.Hash);
hashAlgorithm.Clear();
inputStream.Close();
md5 = md5.Replace("-", "");
return md5;
}
有没有更快的?