C# 使用字节[]读取大文件时出错
可能重复:C# 使用字节[]读取大文件时出错,c#,asp.net,C#,Asp.net,可能重复: 我有一个很大的文件,文件大小为,它给了我一个错误“抛出了'System.OutOfMemoryException'类型的异常” 任何人都有解决此问题的想法或解决方案。请帮忙。 示例代码 private string GetSha1() { string filePath = txtFileName.Text; byte[] filebytes = System.IO.File.ReadAllBytes(filePath);
我有一个很大的文件,文件大小为,它给了我一个错误“抛出了'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);
我在上面代码的下面一行遇到异常
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);
文件路径中的文件大小大于500MB。只需将一个流传递给ComputeHash,即可将整个文件读取到内存中
using(var file = File.Open(path,FileMode.Open))
{
hashValue = hashString.ComputeHash(file);
}
也许您应该使用
System.IO.File.Read
,一次只将文件的一部分读取到字节数组中,而不是一次读取整个文件
请参见关于使用
阅读的示例。您已经大致解释了问题所在。您正试图将500MB文件直接读入字节[]
,因为您使用的是ReadAllBytes()
。除了小文件之外,这实际上不适合任何东西
如果要计算文件的哈希,只需使用流作为参数:
using (filestream f = File.Open(path,FileMode.Open))
{
hashValue = hashString.ComputeHash(f);
}
您的系统是否运行64位操作系统?您的代码是为64位平台构建的吗?系统是否有几GB的可用内存?@HABO-我建议,在这种情况下,这无关紧要,因为没有理由同时将整个文件放入内存。你也是对的,如果文件正在使用,错误永远不会出现。