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 に答える
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 に答える