Seyren Windsor
Seyren Windsor

Reputation: 135

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:

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".

Does this have something to do with the two first ints i did read? Or maybe beacause there isn't a null byte between the first int and the string?

Thanks in advance.

Upvotes: 1

Views: 7870

Answers (2)

T_D
T_D

Reputation: 1728

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

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. 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;
}

Upvotes: 5

itsme86
itsme86

Reputation: 19486

The string in the file should be preceded by a 7-bit encoded length. From MSDN:

Reads a string from the current stream. The string is prefixed with the length, encoded as an integer seven bits at a time.

Upvotes: 4

Related Questions