计算大文件的Md5哈希 [英] Calculating Md5 Hash of Big Files

查看:221
本文介绍了计算大文件的Md5哈希的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想让它变得非常清晰和简单.如果我有1gb的ram并试图计算2gb文件的md5哈希怎么办?目前,我正在通过这种方式进行操作:

I want to make it very clear and simple. What if I have 1gb ram and I'm trying to calculate md5 hash of 2gb file? Currently, I'm doing it this way:

private static string Md5Hash(byte[] input)
{
    byte[] hash = MD5.Create().ComputeHash(input);
    StringBuilder builder = new StringBuilder(32);
    foreach(byte b in hash)
    { builder.Append(b.ToString("X2")); }
    return builder.ToString();
}

// I'm using it like: 'Md5.AsString(File.ReadAllBytes(filePath))'

那么您有什么建议?

推荐答案

而不是在将文件完全加载到内存中之后计算文件的哈希,而要使用占用Stream的重载.

Rather than computing the hash of the file after you've completely loaded it into memory, use the overload that takes a Stream.

byte[] hash;
using (Stream input = File.OpenRead("Filename"))
{
    hash = MD5.Create().ComputeHash(input);
}

这篇关于计算大文件的Md5哈希的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆