【问题标题】:IOException reading a large file from a UNC path into a byte array using .NETIOException 使用 .NET 将大文件从 UNC 路径读取到字节数组中
【发布时间】:2008-12-22 11:58:48
【问题描述】:

我正在使用以下代码尝试从 UNC 路径将大文件 (280Mb) 读入字节数组

public void ReadWholeArray(string fileName, byte[] data)
{
    int offset = 0;
    int remaining = data.Length;

    log.Debug("ReadWholeArray");

    FileStream stream = new FileStream(fileName, FileMode.Open, FileAccess.Read);

    while (remaining > 0)
    {
        int read = stream.Read(data, offset, remaining);
        if (read <= 0)
            throw new EndOfStreamException
                (String.Format("End of stream reached with {0} bytes left to read", remaining));
        remaining -= read;
        offset += read;
    }
}

这会因以下错误而崩溃。

System.IO.IOException: Insufficient system resources exist to complete the requested 

如果我使用本地路径运行它,它工作正常,在我的测试用例中,UNC 路径实际上指向本地框。

有什么想法吗?

【问题讨论】:

    标签: c# .net bytearray large-files unc


    【解决方案1】:

    我怀疑较低的东西正在尝试读取另一个缓冲区,并且一次读取所有 280MB 都失败了。在网络案例中可能需要比本地案例更多的缓冲区。

    我会一次阅读大约 64K,而不是尝试一口气阅读全部内容。这足以避免分块带来的过多开销,但可以避免需要大量缓冲区。

    就我个人而言,我倾向于只阅读到流的末尾,而不是假设文件大小将保持不变。请参阅this question 了解更多信息。

    【讨论】:

    • 您使用 4 页内存作为缓冲区的任何特殊原因?
    • @Robert Davis:重要的大小不是 memory 页面而是 IO 缓冲区。如果您阅读的内容太多以至于需要多个 IO 请求,那有点浪费 - 如果您阅读的内容太少以至于它适合一个有空余空间的请求,那么另一种方式就是浪费。我的经验是 64K 通常是一个很好的折衷方案,但这取决于较低级别发生的具体情况。
    【解决方案2】:

    此外,编写的代码需要将FileStream 放入using 块中。未能处理资源是收到“系统资源不足”的一个非常可能的原因:

    public void ReadWholeArray(string fileName, byte[] data)
    {
        int offset = 0;
        int remaining = data.Length;
    
        log.Debug("ReadWholeArray");
    
        using(FileStream stream = new FileStream(fileName, FileMode.Open, FileAccess.Read))
        {
            while (remaining > 0)
            {
                int read = stream.Read(data, offset, remaining);
                if (read <= 0)
                    throw new EndOfStreamException
                        (String.Format("End of stream reached with {0} bytes left to read", remaining));
                remaining -= read;
                offset += read;
            }
        }
    }
    

    【讨论】:

    • +1。哇,OP > 1 岁,你注意到了这一点。缓冲区大小可能是主要问题,但这将成为一个问题。
    • @Kevin:我对问题进行了编辑(由于 Jon Seigal 的编辑),它直接向我跳了出来。来之不易的教训。
    【解决方案3】:

    看起来创建的数组大小不够。在传入之前分配了多大的数组?或者您是否假设 Read 函数会根据需要重新分配数据数组?它不会。 编辑:呃,也许不是,我只是注意到你得到的例外。现在不确定。

    【讨论】:

      猜你喜欢
      • 2015-06-07
      • 2011-12-03
      • 2015-09-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-08
      • 2013-01-13
      • 2010-10-15
      相关资源
      最近更新 更多