由网友(青春是道明媚的忧伤)分享简介:我有一个Web服务器将读取大型二进制文件(几兆字节)成字节数组。该服务器可以读取多个文件在同一时间(不同的页面请求),所以我在寻找最优化的方式这样做,而不耗费CPU的太多了。低于code不够好?公共字节[] FileToByteArray(字符串文件名){byte []的BUFF = NULL;的FileStre...
我有一个Web服务器将读取大型二进制文件(几兆字节)成字节数组。该服务器可以读取多个文件在同一时间(不同的页面请求),所以我在寻找最优化的方式这样做,而不耗费CPU的太多了。低于code不够好?
公共字节[] FileToByteArray(字符串文件名)
{
byte []的BUFF = NULL;
的FileStream FS =新的FileStream(文件名,
FileMode.Open,
FileAccess.Read);
BR BinaryReader在新= BinaryReader在(FS);
长的numBytes =新的FileInfo(文件名).Length;
BUFF = br.ReadBytes((INT)的numBytes);
返回的buff;
}
解决方案
简单地替换了整个事情:
返回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.
相关推荐
最新文章