Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

EndOfStream for BinaryReader

BinaryReader does not have EndOfStream property. Is it safe to use following code to check if end of stream is reached?

reader.BaseStream.Length>reader.BaseStream.Position

like image 306
melmi Avatar asked Sep 20 '10 15:09

melmi


3 Answers

The easiest way I found is to check the returned value of the BinaryReader's PeekChar() method. If it returns -1, then you reached the end of the stream.

like image 165
Alex Barac Avatar answered Nov 12 '22 00:11

Alex Barac


It depends. There are various stream types that do not implement the Length or Position property, you'd get a NotSupportedException. NetworkStream for example. Of course, if you'd use such a stream then you really do have to know up front how often to call the BinaryReader.Read() method. So, yes, it's fine.

like image 7
Hans Passant Avatar answered Nov 11 '22 23:11

Hans Passant


This won't work as a general solution because it assumes that the BaseStream value supports the Length property. Many Stream implementation do not and instead throw a NotSupportedException. In particular any networking base stream such as HttpRequestStream and NetworkStream

like image 3
JaredPar Avatar answered Nov 11 '22 22:11

JaredPar