【问题标题】:Reading large file using byte[] gives error [duplicate]使用 byte[] 读取大文件会出现错误 [重复]
【发布时间】:2012-08-20 13:33:31
【问题描述】:

可能重复:
Hash SHA1 large files (over 2gb) in C#

我有一个大文件,它给我一个错误“抛出'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。

【问题讨论】:

  • 您的系统是否运行 64 位操作系统?您的代码是为 64 位平台构建的吗?系统是否有几 GB 的可用内存?
  • @HABO - 我建议在这种情况下没关系,因为没有理由将整个文件同时放入内存。

标签: c# asp.net


【解决方案1】:

无需将整个文件读入内存,只需将流传递给 ComputeHash

using(var file = File.Open(path,FileMode.Open))
{
   hashValue = hashString.ComputeHash(file);
}

【讨论】:

    【解决方案2】:

    好吧,您已经解释了问题所在。您正在尝试将 500MB 文件直接读入 byte[],因为您使用的是 ReadAllBytes()。除了小文件之外,这真的不适合任何东西。

    如果您想计算文件的哈希值,只需使用流作为参数:

    using (filestream f = File.Open(path,FileMode.Open))
    {
        hashValue = hashString.ComputeHash(f);
    }
    

    【讨论】:

    • 你也是对的,在你的情况下文件正在使用中永远不会出现错误。
    【解决方案3】:

    也许您应该使用System.IO.File.Read 并一次将文件的一部分读入您的字节数组,而不是一次读取整个文件。

    请参阅MSDN 上的此示例,了解如何使用Read

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-07-11
      • 2018-10-13
      • 1970-01-01
      • 2017-03-18
      • 2015-03-06
      • 2018-06-27
      • 2012-09-22
      相关资源
      最近更新 更多