可能重复:
在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;
}
在上面的代码中,我在下面的行得到了异常。。。。
byte[] filebytes = System.IO.File.ReadAllBytes(filePath);
filePath的文件大小大于500MB。
不需要将整个文件读入内存,只需将流传递给ComputeHash
using(var file = File.Open(path,FileMode.Open))
{
hashValue = hashString.ComputeHash(file);
}
您已经大致解释了问题所在。您正试图将500MB的文件直接读取到byte[]
中,因为您使用的是ReadAllBytes()
。这真的不适合任何东西,除了小文件。
如果你想计算一个文件的散列,只需使用一个流作为参数:
using (filestream f = File.Open(path,FileMode.Open))
{
hashValue = hashString.ComputeHash(f);
}
也许您应该使用System.IO.File.Read
,一次只将文件的一块读取到字节数组中,而不是一次读取整个文件。
请参阅MSDN上关于使用Read
的示例。