Weird Problem Reading Char[] data from a BinaryReader

  • Thread starter Thread starter Mark Olbert
  • Start date Start date
M

Mark Olbert

I ran into a bizarre problem using the NET Framework 2 which I think is a bug (and at least is a very subtle gotcha if it isn't
one).

I have to create "c style" structures from binary data in my application. The utility method I wrote to do this creates a
BinaryReader from the binary data, and then uses the various read methods (e.g., ReadByte(), ReadBytes(length)) to initialize the
structure's fields from the binary data.

One of the fields is a fixed length char array (it's always 512 characters long). So my utility method originally did something like
this:

charArray512 = reader.ReadChars(512);

This worked...sometimes. And sometimes it didn't. After digging into it for several hours I noticed that the problem was
data-related (i.e., some data caused the problem, some didn't). I finally noticed that whenever the binary stream contained
character code 43 (hex 2B) the "code 43" values were being skipped. In other words, the following binary stream (hex):

F0
9B
74
81
2B
12

would be read as: F0 9B 74 81 12. The 2B code was simply skipped.

I have no idea why ReadChars() ignores certain character codes (at least including 2B). My workaround is to use ReadBytes() instead
of ReadChars(), and then convert each byte to a char using Convert.ToChar(). This is slower, but doesn't drop the 2B codes.

BTW, the encoding on the binary stream (and the reader) is set to ASCII.

Can someone explain to me why the 2B codes are being dropped? Is this a bug in ReadChars()?

- Mark
 
Well, you are reading chars, the reader is doing some kind of check or
conversion. So if you want the bytes themselves, you have to use ReadBytes
but instead of converting to char each byte use
System.Text.Encoding.ASCII.GetString(byteArr);
 
if you want the bytes as a string you can use that:

(again)
System.Text.Encoding.ASCII.GetString(byteArr);
 
Back
Top