1

我正在使用以下代码尝试从 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 路径实际上指向本地框。

有什么想法吗?

4

3 回答 3

4

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

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

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

于 2008-12-22T12:07:05.437 回答
1

此外,编写的代码需要将其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;
        }
    }
}
于 2010-03-19T19:18:05.620 回答
0

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

于 2008-12-22T19:03:42.057 回答