在C#中读取一个大字节数组的最佳方法?(Best way to read a large file into a byte array in C#?)

编程入门 行业动态 更新时间:2024-10-26 21:24:59
在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.

更多推荐

本文发布于:2023-07-04 11:11:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1023630.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数组   字节   方法   read   array

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!