读取大文件到C#中的字节数组的最佳方法? [英] Best way to read a large file into a byte array in C#?
本文介绍了读取大文件到C#中的字节数组的最佳方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个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.
这篇关于读取大文件到C#中的字节数组的最佳方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文