在C#中读取一个大字节数组的最佳方法?(Best way to read a large file into a byte array in C#?)
我有一个Web服务器将读取大型二进制文件(几兆字节)到字节数组。 服务器可能同时读取几个文件(不同的页面请求),所以我正在寻找最优化的方式来执行此操作,而不会对CPU太多征税。 代码是否足够好?
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; }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; }最满意答案
只需用以下方式替换整个事物:
return File.ReadAllBytes(fileName);但是,如果您担心内存消耗,则不应一次将整个文件读入内存。 你应该这样做的大块。
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.
更多推荐
发布评论