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

How*_*amp 17 c# hash md5 file md5-file

如何在不将整个文件加载到内存中的情况下,逐个读取任意文件并逐个处理(意味着逐字节或其他一些可提供最佳读取性能的块大小)?处理的一个示例是生成文件的MD5哈希,尽管答案可以应用于任何操作.

我想拥有或写这个,但如果我能获得现有代码也会很棒.

(C#)

Dar*_*rov 26

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

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.
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 这会将1KB(或chunkSize字节)加载到内存中.编辑:他还意味着没有写出整个`缓冲区'!只有从索引0到索引`bytesRead`的字节. (4认同)
  • @Darin我尝试了此代码,但*无法正确读取最后一个块*。如果最后一块小于`chunkSize`,它将垃圾值保留在缓冲区中。 (2认同)

Ver*_*cas 10

System.IO.FileStream不会将文件加载到内存中.
此流是可搜索的,MD5哈希算法也不必加载流(文件)介绍内存.

请替换file_path为您的文件的路径.

byte[] hash = null;

using (var file = new FileStream(file_path, FileMode.Open))
{
    using (var md5 = new System.Security.Cryptography.MD5CryptoServiceProvider())
    {
        hash = md5.ComputeHash(stream);
    }
}
Run Code Online (Sandbox Code Playgroud)

在这里,您的MD5哈希将存储在hash变量中.