C# - Stream/FileStream EOF

eve picture eve · Feb 16, 2011 · Viewed 20.6k times · Source

Is anyone familiar with a way to find out you're at the end of the file? I'm using BinaryReader and tried PeekChar - but it throws an exception. Any other suggestions?

Thanks.

Answer

Marc Gravell picture Marc Gravell · Feb 16, 2011

From a Stream, if you Read(buffer, offset, count) you'll get a non-positive result, and if you Peek() you'll get a negative result.

With a BinaryReader, the documentation suggests that PeekChar() should return negative:

Return Value

Type: System.Int32 The next available character, or -1 if no more characters are available or the stream does not support seeking.

are you sure this isn't a corrupt stream? i.e. the remaining data cannot form a complete char from the given encoding?