【问题标题】:Readstring from BinaryReader in C# Doesn't read the first byte从 C# 中的 BinaryReader 读取字符串不读取第一个字节
【发布时间】:2014-08-29 23:42:36
【问题描述】:

我正在使用 C# 中 System.IO 中的 BinaryReader 读取二进制文件,但是,当使用 ReadString 时,它不会读取第一个字节,代码如下:

using (var b = new BinaryReader(File.Open(open.FileName, FileMode.Open)))
{
    int version = b.ReadInt32();
    int chunkID = b.ReadInt32();
    string objname = b.ReadString();
}

并不是什么难事,首先它读取两个整数,但是应该返回 objame 的字符串是“bat”,而是返回“at”。

这与我读过的前两个整数有关吗?或者可能是因为第一个 int 和字符串之间没有空字节?

提前致谢。

【问题讨论】:

  • 你确定第一个字符串之前的整数实际上是 4 个字节长吗?也许您应该发布写入文件的代码?

标签: c# string binaryreader


【解决方案1】:

文件中的字符串前面应该有一个 7 位的编码长度。来自MSDN

从当前流中读取一个字符串。字符串以长度为前缀,编码为整数,一次七位。

【讨论】:

    【解决方案2】:

    正如itsme86 在他的回答BinaryReader.ReadString() 中所写的那样,它有自己的工作方式,只有在创建的文件使用BinaryWriter.Write(string val) 时才应该使用它。

    在您的情况下,您可能有一个固定大小的字符串,您可以在其中使用BinaryReader.ReadChars(int count),或者您有一个空终止的字符串,您必须在遇到 0 字节之前读取该字符串。这是读取空终止字符串的一种可能的扩展方法:

    public static string ReadNullTerminatedString(this System.IO.BinaryReader stream)
    {
        string str = "";
        char ch;
        while ((int)(ch = stream.ReadChar()) != 0)
            str = str + ch;
        return str;
    }
    

    【讨论】:

    • 嗯,它不必是BinaryWriter.Write,它只需要是pascal string
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-06-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多