C# 检查文件的二进制读取器结尾

标签 c# binaryfiles binaryreader

我正在为我的二进制阅读器寻找一种方法来检查我是否已到达文件末尾,一个建议是这样使用 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/

相关文章:

c# - 代码分析找不到引用,失败并出现 0 个错误或警告

c# - 为什么 channel "Debug"和 "Analytic"不适用于我的 ETW-EventSource 实现?

c++ - 需要在二进制模式下使用 T=unsigned char 在流上使用 noskipws 吗?

c# - 动态操作自适应 IInputStream (MPEG-DASH)

c# - 语言间的方法差异(Python->C#)

c# - 自动高度结合 MaxHeight

c# - GetShortPathNameA 在 C# 中不起作用

java - 在 Java 中读取 C++ 二进制文件

c++ - 使用二进制文件访问违规读取位置

c# - 一种优雅的方式来使用(所有字节的)BinaryReader?