How can I read/stream a file without loading the entire file into memory?

后端 未结 5 1364
太阳男子
太阳男子 2020-11-27 18:47

How can I read an arbitrary file and process it \"piece by piece\" (meaning byte by byte or some other chunk size that would give the best read performance) without loading

5条回答
  •  没有蜡笔的小新
    2020-11-27 19:02

    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));
    

    As I understand the functions used here (specifically BinaryReader.ReadBytes), there is no need to track how many bytes you've read. You just need to know the length and current position for the while loop -- which the stream tells you.

提交回复
热议问题