gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 03:13:00 24 4
gpt4 key购买 nike

如何在不将整个文件加载到内存的情况下读取任意文件并“逐个”处理它(意思是逐字节或其他可以提供最佳读取性能的 block 大小)?处理的一个例子是生成文件的 MD5 散列,尽管答案可以适用于任何操作。

我想拥有或编写这个,但如果我可以获得现有代码,那也很棒。

(c#)

最佳答案

下面是一个示例,说明如何在不将整个内容加载到内存的情况下以 1KB 的 block 读取文件:

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.
}
}

关于c# - 如何在不将整个文件加载到内存的情况下读取/流式传输文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6865890/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com