using (BinaryReader reader = new BinaryReader(File.Open("data.bin", FileMode.Open))) { long position = reader.BaseStream.Position; // store current position int value = reader.ReadInt32(); // read integer value reader.BaseStream.Position = position; // restore previous position byte[] data = reader.ReadBytes(10); // read 10 bytes of data from the same position }
byte[] buffer = new byte[1024]; using (BinaryReader reader = new BinaryReader(File.Open("data.bin", FileMode.Open))) { while (reader.BaseStream.Position != reader.BaseStream.Length) { long position = reader.BaseStream.Position; // store current position int length = reader.ReadInt32(); // read length of data reader.BaseStream.Position = position; // restore previous position byte[] data = reader.ReadBytes(length); // read data from the same position // process the data } }This example shows how to read multiple chunks of binary data from a file using the PreserveCurrentPosition property. The length of each data chunk is read from the file before reading the actual data, so the position of the stream needs to be preserved and restored to read the data correctly. The System.IO.BinaryReader class belongs to the .NET Framework class library.