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

标签 c# file hash md5 md5-file

如何在不将整个文件加载到内存的情况下读取任意文件并“逐个”处理它(意思是逐字节或其他可以提供最佳读取性能的 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/

相关文章:

.exe 文件的哈希值

perl - 如何用 perl 写得更好

python - 如何保留包含特定字符串的行并从 .txt 文件中删除其他行?

c# - 如何在 C# (linq) 上创建困难组?

c# - 在让其他线程调用它之前让当前线程完成使用该函数 C#

c# - 更复杂(现实生活)的模型绑定(bind)?

c# - 如何提高将 clob 数据写入文件的速度

java - 将数组存储在 Set 中并避免重复

c# - TFS 文件更改通知

c# - `foreach`如何遍历一个二维数组?