eve
eve

Reputation: 81

C# - Stream/FileStream EOF

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.

Upvotes: 8

Views: 24975

Answers (4)

Nepaluz
Nepaluz

Reputation: 697

Checking whether the position of the reader is less than its length does the trick

While BinReader.Position < BinReader.Length
{
 ... BinReader.Read() ...
}

Upvotes: 1

xanatos
xanatos

Reputation: 111830

I'll add my suggestion: if you don't need the "encoding" part of the BinaryReader (so you don't use the various ReadChar/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. The iso-8859-1 encoding is a one-byte-per-character encoding that maps 1:1 all the first 256 characters of Unicode (so the byte 254 is the char 254 for example)

Upvotes: 0

WiseGuyEh
WiseGuyEh

Reputation: 19080

If your stream supports seeking (check this using the BaseStream.CanSeek property), check the Position property of the BaseStream, like so:

if (myBinaryReader.BaseStream.CanSeek){
   bool atEnd = (myBinaryReader.BaseStream.Position == myBinaryReader.BaseStream.Length - 1)
}

Upvotes: 2

Marc Gravell
Marc Gravell

Reputation: 1062550

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?

Upvotes: 11

Related Questions