1

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.

1
  • 3
    are you sure the ints before the first string are actually 4 bytes long? Perhaps you should post the code that writes the file? Commented Aug 29, 2014 at 23:50

2 Answers 2

5

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;
}
Sign up to request clarification or add additional context in comments.

1 Comment

Well it doesn't have to be made with BinaryWriter.Write, it just has to be a pascal string.
4

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.