代码之家  ›  专栏  ›  技术社区  ›  Matt

使用.NET将大型文件从UNC路径读入字节数组时发生IOException

  •  1
  • Matt  · 技术社区  · 17 年前

    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路径实际上指向本地框。

    3 回复  |  直到 16 年前
        1
  •  4
  •   Community Mohan Dere    9 年前

    我怀疑底层有人试图读入另一个缓冲区,一次读取所有280MB都失败了。网络情况下可能需要比本地情况下更多的缓冲区。

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

    this question 了解更多信息。

        2
  •  1
  •   John Saunders    16 年前

    此外,编写的代码需要将 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;
            }
        }
    }
    
        3
  •  0
  •   Joel Lucsy    17 年前

    编辑:呃,也许不是,我只是注意到了你得到的例外。现在还不确定。

    推荐文章