C# - 流/文件流 EOF
有谁熟悉如何找出您位于文件末尾的方法吗? 我正在使用 BinaryReader 并尝试了 PeekChar - 但它引发了异常。还有其他建议吗?
谢谢。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
从
Stream
中,如果您Read(buffer, offset, count)
,您将得到一个非正结果,如果您Peek()
> 你会得到一个负面的结果。使用
BinaryReader
,文档 建议PeekChar()
应返回负数:您确定这不是损坏流吗?即剩余数据无法根据给定编码形成完整的
char
?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?如果您的流支持查找(使用 BaseStream.CanSeek 属性检查此项),请检查 BaseStream 的 Position 属性,如下所示:
If your stream supports seeking (check this using the BaseStream.CanSeek property), check the Position property of the BaseStream, like so:
检查读取器的位置是否小于其长度就可以了
Checking whether the position of the reader is less than its length does the trick
我将添加我的建议:如果您不需要
BinaryReader
的“编码”部分(因此您不使用各种ReadChar
/ReadChars
/ReadString
),那么您可以使用永远不会抛出异常并且始终为每个字符一个字节的编码器。Encoding.GetEncoding("iso-8859-1")
非常适合此目的。iso-8859-1
编码是一种每字符一个字节的编码,它 1:1 映射 Unicode 的所有前 256 个字符(因此byte
254 是例如char
254)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)