在 C# 中将大文件读入字节数组的最佳方法? [英] Best way to read a large file into a byte array in C#?
本文介绍了在 C# 中将大文件读入字节数组的最佳方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个网络服务器,可以将大型二进制文件(几兆字节)读入字节数组.服务器可能同时读取多个文件(不同的页面请求),因此我正在寻找最优化的方法来执行此操作,而不会对 CPU 造成过多负担.下面的代码够好吗?
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屋!
查看全文