C# 计算文件 MD5

计算文件 MD5

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
static string CalculateMd5(string filename)
{
using (var md5 = System.Security.Cryptography.MD5.Create())
{
using (var stream = File.OpenRead(filename))
{
var hash = md5.ComputeHash(stream);
return BitConverter.ToString(hash).Replace("-", "").ToLowerInvariant();
}
}
}
// Verify a hash against a string.
static bool VerifyMd5Hash(string filename, string hash)
{
// Hash the input.
string hashOfInput = CalculateMd5(filename);

// Create a StringComparer an compare the hashes.
StringComparer comparer = StringComparer.OrdinalIgnoreCase;

if (0 == comparer.Compare(hashOfInput, hash))
{
return true;
}
else
{
return false;
}
}