且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

读取大文件到C#中的字节数组的***方法?

更新时间:2023-11-15 20:32:58

简单地替换了整个事情:

 返回File.ReadAllBytes(文件名);
 

不过,如果您担心内存消耗,你应该的没有的读取整个文件到内存中一次全部所有。你应该这样做,在块。

I have a web server which will read large binary files (several megabytes) into byte arrays. The server could be reading several files at the same time (different page requests), so I am looking for the most optimized way for doing this without taxing the CPU too much. Is the code below good enough?

public byte[] FileToByteArray(string fileName)
{
    byte[] buff = null;
    FileStream fs = new FileStream(fileName, 
                                   FileMode.Open, 
                                   FileAccess.Read);
    BinaryReader br = new BinaryReader(fs);
    long numBytes = new FileInfo(fileName).Length;
    buff = br.ReadBytes((int) numBytes);
    return buff;
}

Simply replace the whole thing with:

return File.ReadAllBytes(fileName);

However, if you are concerned about the memory consumption, you should not read the whole file into memory all at once at all. You should do that in chunks.