我需要计算相当大的文件(千兆字节)的校验和.这可以使用以下方法完成:
private byte[] calcHash(string file)
{
System.Security.Cryptography.HashAlgorithm ha = System.Security.Cryptography.MD5.Create();
FileStream fs = new FileStream(file, FileMode.Open, FileAccess.Read);
byte[] hash = ha.ComputeHash(fs);
fs.Close();
return hash;
}
Run Code Online (Sandbox Code Playgroud)
但是,文件通常是以缓冲方式预先写入的(比如一次写入32mb).我确信我看到了一个覆盖哈希函数,它允许我在写入的同时计算MD5(或其他)哈希,即:计算一个缓冲区的哈希值,然后将得到的哈希值提供给下一次迭代.
像这样的东西:(伪代码)
byte [] hash = new byte [] { 0,0,0,0,0,0,0,0 };
while(!eof)
{
buffer = readFromSourceFile();
writefile(buffer);
hash = calchash(buffer, hash);
}
Run Code Online (Sandbox Code Playgroud)
hash现在通过在整个文件上运行calcHash函数来实现.
现在,我无法在.Net 3.5框架中找到任何覆盖,我在做什么?它从来没有存在过,或者我只是在搜索时很糟糕?同时进行写入和校验和计算的原因是因为大文件有意义.
可能重复:
在C#中散列SHA1大文件(超过2GB)
我有一个大型文件的大文件,它给我错误"抛出类型'System.OutOfMemoryException'的异常."
任何人都有解决此问题的想法或解决方案.请帮忙.示例代码....
private string GetSha1()
{
string filePath = txtFileName.Text;
byte[] filebytes = System.IO.File.ReadAllBytes(filePath);
byte[] hashValue;
SHA1Managed hashString = new SHA1Managed();
string hex = "";
hashValue = hashString.ComputeHash(filebytes);
foreach (byte x in hashValue)
{
hex += String.Format("{0:x2}", x);
}
return hex;
}
Run Code Online (Sandbox Code Playgroud)
我在上面的代码中在下面的行中得到例外....
byte[] filebytes = System.IO.File.ReadAllBytes(filePath);
Run Code Online (Sandbox Code Playgroud)
filePath的文件大小> 500MB.