Is it possible to detect if BinaryReader.ReadBytes(int) reaches the end of a stream?

402 views Asked by At

Most of BinaryReader's read methods throw an EndOfStreamException if it reaches the end of a stream, but strangely the ReadBytes method doesn't. But what if I do still want to throw an EndOfStreamException? How do I detect that?

I could use the BaseStream.Position property, but the steam I'm using does not support seeking, so this would throw a NotSupportedException.

1

There are 1 answers

0
JochCool On BEST ANSWER

I found the answer while typing my question. It turns out that, if the end of the stream is reached, the method simply returns a shorter array. So this is how you can detect it:

byte[] bytes = binaryReader.ReadBytes(someNumber);
if (bytes.Length != someNumber)
    throw new EndOfStreamException(); // Or do something else.