20

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

我想拥有或写这个,但如果我能得到现有的代码,那也很棒。

(C#)

4

5 回答 5

31

下面是一个示例,说明如何在不将全部内容加载到内存的情况下以 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.
    }
}
于 2011-07-28T21:29:10.833 回答
11

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

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

byte[] hash = null;

using (var stream = new FileStream(file_path, FileMode.Open))
{
    using (var md5 = new System.Security.Cryptography.MD5CryptoServiceProvider())
    {
        hash = md5.ComputeHash(stream);
    }
}

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

于 2011-07-28T21:28:50.020 回答
4
   int fullfilesize = 0;// full size of file
    int DefaultReadValue = 10485760; //read 10 mb at a time
    int toRead = 10485760;
    int position =0;

  //  int 
 //   byte[] ByteReadFirst = new byte[10485760];

    private void Button_Click(object sender, RoutedEventArgs e)
    {
        using (var fs = new FileStream(@"filepath", FileMode.Open, FileAccess.Read))
        {
            using (MemoryStream requestStream = new MemoryStream())
            {


                fs.Position = position;

                if (fs.Position >= fullfilesize)
                {
                    MessageBox.Show(" all done");
                    return;
                }
                System.Diagnostics.Debug.WriteLine("file position" + fs.Position);

                if (fullfilesize-position < toRead)
                {
                    toRead = fullfilesize - position;
                    MessageBox.Show("last time");
                }
                System.Diagnostics.Debug.WriteLine("toread" + toRead);
                int    bytesRead;
                byte[] buffer = new byte[toRead];
                int offset = 0;
                position += toRead;
                while (toRead > 0 && (bytesRead = fs.Read(buffer, offset, toRead)) > 0)
                {
                    toRead -= bytesRead;
                    offset += bytesRead;
                }

                toRead = DefaultReadValue;


            }
        }
    }

复制 Darin 的,这个方法会读取 10mb 个块直到文件结束

于 2014-01-16T12:52:06.277 回答
2
const int MAX_BUFFER = 1024;
byte[] Buffer = new byte[MAX_BUFFER];
int BytesRead;
using (System.IO.FileStream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read))
    while ((BytesRead = fileStream.Read(Buffer, 0, MAX_BUFFER)) != 0)
    {
        // Process this chunk starting from offset 0 
        // and continuing for bytesRead bytes!
    }
于 2011-07-28T21:34:11.137 回答
1
const long numberOfBytesToReadPerChunk = 1000;//1KB
using (BinaryReader fileData = new BinaryReader(File.OpenRead(aFullFilePath))
    while (fileData.BaseStream.Position - fileData.BaseStream.Length > 0)
        DoSomethingWithAChunkOfBytes(fileData.ReadBytes(numberOfBytesToReadPerChunk));

据我了解这里使用的函数(特别BinaryReader.ReadBytes是),没有必要跟踪你读了多少字节。您只需要知道 while 循环的长度和当前位置 - 流会告诉您。

于 2016-06-30T17:18:41.670 回答