如何在Windows应用商店应用中使用C#计算大文件的哈希(MD5或SHA)

时间:2012-11-23 18:42:17

标签: c# windows microsoft-metro

问题:

“如果您尝试使用包含大文件的缓冲区使用metod HashData(IBuffer)在Windows 8 Metro App中计算md5或sha,则会收到OutOfMemoryException,因为缓冲区非常大(包含字节中的副本)原始文件)。“

SOLUTION:

//NB: "file" is a "StorageFile" previously openedHashAlgorithmProvider md5 = Windows.Security.Cryptography.Core.HashAlgorithmProvider.OpenAlgorithm(HashAlgorithmNames.Md5);
//in this example I use HashAlgorithmNames.Md5, you can replace it with HashAlgorithmName.Sha1, etc...

HashAlgorithmProvider alg = Windows.Security.Cryptography.Core.HashAlgorithmProvider.OpenAlgorithm(HashAlgorithmNames.Md5);
var stream = await file.OpenStreamForReadAsync();
var inputStream = stream.AsInputStream();
uint capacity = 100000000;
Windows.Storage.Streams.Buffer buffer = new Windows.Storage.Streams.Buffer(capacity);
var hash = alg.CreateHash();

while (true)
{
    await inputStream.ReadAsync(buffer, capacity, InputStreamOptions.None);
    if (buffer.Length > 0)
        hash.Append(buffer);
    else
        break;
}

string hashText = CryptographicBuffer.EncodeToHexString(hash.GetValueAndReset()).ToUpper();

inputStream.Dispose();
stream.Dispose();

我希望这有用:)

0 个答案:

没有答案