ファイル全体をメモリにロードせずに、任意のファイルを読み取って「ピースごと」(バイトごと、または最高の読み取りパフォーマンスを提供する他のチャンクサイズを意味します) に処理するにはどうすればよいですか? 処理の例は、ファイルの MD5 ハッシュを生成することですが、答えはどの操作にも当てはまります。
これを持っているか書きたいのですが、既存のコードを入手できればそれも素晴らしいでしょう。
(c#)
コンテンツ全体をメモリにロードせずに、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.
}
}
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
ます。
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!
}
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 ループの長さと現在の位置を知る必要があるだけです。ストリームが教えてくれます。