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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10942848/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 15:52:27  来源:igfitidea点击:

C# checking for binary reader end of file

c#binaryfilesbinaryreader

提问by MxLDevs

I was searching for a way to check whether I've reached the end of a file for my binary reader and one suggestion was to use PeekChar as such

我正在寻找一种方法来检查我的二进制阅读器是否已到达文件末尾,一个建议是使用 PeekChar

while (inFile.PeekChar() > 0)
{
    ...
}

However, it looks like I've run into an issue

但是,看起来我遇到了问题

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

So maybe PeekChar isn't the best way to do it, and I don't think it should even be used that way because I'm checking the current position of my reader and not really what the next character is supposed to be.

所以也许 PeekChar 不是最好的方法,我认为它甚至不应该这样使用,因为我正在检查我的读者的当前位置,而不是真正的下一个角色应该是什么。

采纳答案by MxLDevs

There is a more accurate way to check for EOF when working with binary data. It avoids all of the encoding issues that come with the PeekCharapproach and does exactly what is needed: to check whether the position of the reader is at the end of the file or not.

在处理二进制数据时,有一种更准确的方法来检查 EOF。它避免了该PeekChar方法带来的所有编码问题,并完全满足需要:检查读取器的位置是否在文件末尾。

while (inFile.BaseStream.Position != inFile.BaseStream.Length)
{
   ...
}

回答by Un Peu

Wrapping it into a Custom Extension Methodthat'll extend the BinaryReaderclass by adding the missing EOF method.

将其包装到自定义扩展方法中,该方法将通过添加缺少的 EOF 方法来扩展BinaryReader类。

public static class StreamEOF {

    public static bool EOF( this BinaryReader binaryReader ) {
        var bs = binaryReader.BaseStream;
        return ( bs.Position == bs.Length);
    }
}

So now you can just write:

所以现在你可以写:

while (!infile.EOF()) {
   // Read....
}

:) ... assuming you have created infilesomewhere like this:

:) ...假设你已经在这样的地方创建了infile

var infile= new BinaryReader();

Note: varis implicit typing. Happy to found it - it's other puzzle piece for well styled code in C#. :D

注意:var是隐式类型。很高兴找到它 - 它是 C# 中风格良好的代码的另一个拼图。:D

回答by user1803917

This work for me:

这对我有用:

using (BinaryReader br = new BinaryReader(File.Open(fileName,   
FileMode.Open))) {
            //int pos = 0;
            //int length = (int)br.BaseStream.Length;
            while (br.BaseStream.Position != br.BaseStream.Length) {
                string nume = br.ReadString ();
                string prenume = br.ReadString ();
                Persoana p = new Persoana (nume, prenume);
                myArrayList.Add (p);
                Console.WriteLine ("ADAUGAT XXX: "+ p.ToString());
                //pos++;
            }
        }

回答by xanatos

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. You pass it as a parameter of the BinaryReaderconstructor. 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 byte254 is the char254 for example)

我将添加我的建议:如果您不需要 BinaryReader 的“编码”部分(因此您不使用各种 ReadChar/ReadChars/ReadString),那么您可以使用永远不会抛出的编码器每个字符总是一个字节。Encoding.GetEncoding("iso-8859-1")非常适合这个。您将它作为BinaryReader构造函数的参数传递。iso-8859-1 编码是每字符一个字节的编码,它以 1:1 映射 Unicode 的所有前 256 个字符(例如,byte254 是char254)