Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/288.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C#不';t读取第一个字节_C#_String_Binaryreader - Fatal编程技术网

C#不';t读取第一个字节

C#不';t读取第一个字节,c#,string,binaryreader,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

我正在使用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();
}
不是很难,首先它读取两个整数,但是应该返回对象的字符串是“bat”,而它返回“at”

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


提前感谢。

文件中的字符串前面应加上7位编码长度。发件人:

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


文件中的字符串应以7位编码长度开头。发件人:

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


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

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

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

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

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

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

您确定第一个字符串前的int实际上是4字节长吗?也许您应该发布写入文件的代码?您确定第一个字符串前的int实际上是4字节长吗?也许你应该发布写文件的代码?它不一定要用
BinaryWriter.Write
,它只需要是一个。它不一定要用
BinaryWriter.Write
,它只需要是一个。