我正在为我的二进制阅读器寻找一种方法来检查我是否已到达文件末尾,一个建议是这样使用 PeekChar
while (inFile.PeekChar() > 0)
{
...
}
但是,看起来我遇到了问题
Unhandled Exception: System.ArgumentException: The output char buffer is too sma ll to contain the decoded characters, encoding 'Unicode (UTF-8)' fallback 'Syste m.Text.DecoderReplacementFallback'. Parameter name: chars at System.Text.Encoding.ThrowCharsOverflow() at System.Text.Encoding.ThrowCharsOverflow(DecoderNLS decoder, Boolean nothin gDecoded) at System.Text.UTF8Encoding.GetChars(Byte* bytes, Int32 byteCount, Char* char s, Int32 charCount, DecoderNLS baseDecoder) at System.Text.DecoderNLS.GetChars(Byte* bytes, Int32 byteCount, Char* chars, Int32 charCount, Boolean flush) at System.Text.DecoderNLS.GetChars(Byte[] bytes, Int32 byteIndex, Int32 byteC ount, Char[] chars, Int32 charIndex, Boolean flush) at System.Text.DecoderNLS.GetChars(Byte[] bytes, Int32 byteIndex, Int32 byteC ount, Char[] chars, Int32 charIndex) at System.IO.BinaryReader.InternalReadOneChar() at System.IO.BinaryReader.PeekChar()
所以也许 PeekChar 不是最好的方法,我认为它甚至不应该那样使用,因为我正在检查我的阅读器的当前位置,而不是下一个字符应该是什么是。
最佳答案
在处理二进制数据时,有一种更准确的方法来检查 EOF。它避免了 PeekChar
方法带来的所有编码问题,并且完全满足需要:检查读取器的位置是否在文件末尾。
while (inFile.BaseStream.Position != inFile.BaseStream.Length)
{
...
}
关于C# 检查文件的二进制读取器结尾,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10942848/