来自C#中BinaryReader的readstring不读取第一个字节

时间:2014-08-29 23:42:36

标签: c# string binaryreader

我正在使用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和字符串之间没有空字节?

提前致谢。

2 个答案:

答案 0 :(得分:3)

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

  

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

答案 1 :(得分:3)

正如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;
}
相关问题