简体   繁体   English

C#中BinaryReader的Readstring不读取第一个字节

[英]Readstring from BinaryReader in C# Doesn't read the first byte

I'm reading a binary file using BinaryReader from System.IO in C#, however, when using ReadString it doesn't read the first byte, here is the code: 我正在使用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();
}

Is not something really hard, first it reads two ints, but the string that is supposed to return the objame is "bat", and instead it returns "at". 并不是很困难,首先它读取两个int,但是应该返回objame的字符串是“ bat”,而返回“ at”。

Does this have something to do with the two first ints i did read? 这与我读过的前两个int有关吗? Or maybe beacause there isn't a null byte between the first int and the string? 还是因为第一个int与字符串之间没有空字节?

Thanks in advance. 提前致谢。

The string in the file should be preceded by a 7-bit encoded length. 文件中的字符串应以7位编码长度开头。 From MSDN : MSDN

Reads a string from the current stream. 从当前流中读取一个字符串。 The string is prefixed with the length, encoded as an integer seven bits at a time. 该字符串以长度为前缀,一次编码为7位整数。

As itsme86 wrote in his answer BinaryReader.ReadString() has its own way of working and it should only be used when the created file used BinaryWriter.Write(string val) . 正如itsme86在他的答案中所写的那样, BinaryReader.ReadString()有其自己的工作方式,仅当创建的文件使用BinaryWriter.Write(string val)时才应使用它。

In your case you probably have either a fixed size string where you could use BinaryReader.ReadChars(int count) or you have a null terminated string where you have to read until a 0 byte is encountered. 在您的情况下,您可能有一个固定大小的字符串可以在其中使用BinaryReader.ReadChars(int count)或者您有一个以null结尾的字符串,在其中必须读取直到遇到0字节为止。 Here is a possible extension method for reading a null terminated string: 这是读取空终止字符串的可能的扩展方法:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM