C# - Stream/FileStream EOF

给你一囗甜甜゛ 提交于 2019-12-10 03:41:45

问题


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.


回答1:


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?




回答2:


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)
}



回答3:


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

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



回答4:


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)




回答5:


While BinReader.PeekChar() > 0
{
...
}


来源:https://stackoverflow.com/questions/5016403/c-sharp-stream-filestream-eof

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!