Is it safe to use Stream.Seek when a BinaryReader is open?

Matthieu Durut picture Matthieu Durut · Oct 2, 2013 · Viewed 7.6k times · Source

Because of the under the hood buffering strategy of BinaryReader, it is unclear to me whether is it ok or not to read an offset stored in a stream, then reposition the stream at this offset to resume the streaming.

As an example, is the following code ok:

using (var reader = new CustomBinaryReader(inputStream))
{
   var offset= reader.ReadInt32();
   reader.BaseStream.Seek(offset, SeekOrigin.Begin);

   //Then resume reading the streaming
}

Or should I close the first binary reader before Seeking the stream and then reopen a second reader ?

int offset;
using (var firstReader = new CustomBinaryReader(inputStream))
{
   offset= firstReader.ReadInt32();
}
inputStream.Seek(offset, SeekOrigin.Begin);
using (var secondReader = new CustomBinaryReader(inputStream))
{
   //Then resume reading the streaming
}

Answer

Hans Passant picture Hans Passant · Oct 2, 2013

BinaryReader does use a buffer but only to read enough bytes from the base stream to convert a value. In other words, ReadInt32() will buffer 4 bytes first, ReadDecimal() will buffer 16 bytes first, etcetera. ReadString() is the trickier method but it has counter-measures as well, a string is encoded in the file by BinaryWriter which writes the string length first. So that BinaryReader knows exactly how many bytes to buffer before converting the string.

So the buffer is always empty after one of the ReadXxx() method returns and calling Seek() on the BaseStream is fine. Also the reason that Microsoft didn't need to override the Seek() method.

The cautionary note in the MSDN article is appropriate, you certainly will read that "offset" value more than once if you call a ReadXxx() method after the Seek() call. I however assume that was entirely intentional.