且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在不将整个文件加载到内存中的情况下读取/流式传输文件?

更新时间:2023-09-10 20:07:10

这里有一个示例,说明如何在不将整个内容加载到内存中的情况下以 1KB 的块读取文件:

Here's an example of how to read a file in chunks of 1KB without loading the entire contents into memory:

const int chunkSize = 1024; // read the file by chunks of 1KB
using (var file = File.OpenRead("foo.dat"))
{
    int bytesRead;
    var buffer = new byte[chunkSize];
    while ((bytesRead = file.Read(buffer, 0, buffer.Length)) > 0)
    {
        // TODO: Process bytesRead number of bytes from the buffer
        // not the entire buffer as the size of the buffer is 1KB
        // whereas the actual number of bytes that are read are 
        // stored in the bytesRead integer.
    }
}