C# - Stream/FileStream EOF

2019-04-25 12:14发布

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.

标签: c# stream eof
5条回答
我欲成王,谁敢阻挡
2楼-- · 2019-04-25 12:45

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?

查看更多
淡お忘
3楼-- · 2019-04-25 12:51
While BinReader.PeekChar() > 0
{
...
}
查看更多
We Are One
4楼-- · 2019-04-25 13:02

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

While BinReader.Position < BinReader.Length
{
 ... BinReader.Read() ...
}
查看更多
趁早两清
5楼-- · 2019-04-25 13:02

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)

查看更多
Luminary・发光体
6楼-- · 2019-04-25 13:04

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)
}
查看更多
登录 后发表回答