3

When reading in a Binary file using System.IO.BinaryReader the byte order seems to be unaffected when using any of the multi-byte Read methods.

BinaryReader br = new BinaryReader(fs, System.Text.Encoding.BigEndianUnicode);

and

BinaryReader br = new BinaryReader(fs, System.Text.Encoding.Unicode);

are producing the same results for me.

This is causing me a lot of frustration because I have to reverse the byte order constantly while reading in data structures.

Screenshot - Big Endian Unicode

Screenshot - Little Endian Unicode

I've tested this on .NET 3 through 4.5

3
  • I assume the BinaryRead only works on textfiles, but from the chunks in your code the file seems to be binary. Then as far as I know you have to handcode it using the Convert class Commented Oct 16, 2012 at 4:51
  • Or take a look here: stackoverflow.com/questions/80784/… Commented Oct 16, 2012 at 4:52
  • What is the result if you specify encoding for the reader as well? Commented Oct 16, 2012 at 5:01

1 Answer 1

8

BinaryReader only uses the Encoding when handling string data (pretty much, just ReadString()). ReadBytes etc do not involve Encoding - it just reads the binary data. Since you only call ReadBytes, this (Encoding) never gets a look-in.

If the data is out-of-order, then it sounds like the file wasn't created with BinaryWriter. If it wasn't created with BinaryWriter then BinaryReader probably isn't all that useful - you could just use Stream.

Sign up to request clarification or add additional context in comments.

1 Comment

A BinaryReader-like class can still be useful if you know the format - but if you need to switch endianness, EndianBinaryReader is what you want, from MiscUtil :)

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.