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.
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.
From a
Stream
, if youRead(buffer, offset, count)
you'll get a non-positive result, and if youPeek()
you'll get a negative result.With a
BinaryReader
, the documentation suggests thatPeekChar()
should return negative:are you sure this isn't a corrupt stream? i.e. the remaining data cannot form a complete
char
from the given encoding?Checking whether the position of the reader is less than its length does the trick
I'll add my suggestion: if you don't need the "encoding" part of the
BinaryReader
(so you don't use the variousReadChar
/ReadChars
/ReadString
) then you can use an encoder that won't ever throw and that is always one-byte-per-char.Encoding.GetEncoding("iso-8859-1")
is perfect for this. Theiso-8859-1
encoding is a one-byte-per-character encoding that maps 1:1 all the first 256 characters of Unicode (so thebyte
254 is thechar
254 for example)If your stream supports seeking (check this using the BaseStream.CanSeek property), check the Position property of the BaseStream, like so: