BinaryWriter.Write() adding extra bytes?

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

Hello,

I am writing a binary file using C# and then reading it using eVC++ but I am
running into a few oddities which I notice when hex editing the file created
by C#.

Here’s one thing I’ve noticed. When using the following code I would expect
the file to only contain “(null)DEVS(null)†when it actually contains
“0x06(null)DEVS(null)â€. Where’d that 0x06 come from?

FileStream d_fs = new FileStream(deviceFile, FileMode.Create,
FileAccess.ReadWrite);
BinaryWriter d_bw = new BinaryWriter(d_fs);

d_bw.Write((string)"\0DEVS\0");

d_bw.Close();
d_fs.Close();

Actual file is
"..DEVS." == 0x06 0x00 0x44 0x45 0x56 0x53 0x00

I had noticed extra 0x06, 0x04 and 0x05 scatter throughout the file but they
seem to added when I call a Write(). So, rather than do a whole bunch of
Write()s I created a StringBuilder and wrote it out once I was do appending
to it. Now I get an extra 0x4C at the beginning of the string created by
StringBuilder.

What’s going on? Does BinaryWriter.Write() put add a header byte to tell it
the type of the following data? I’m sure this wouldn’t be an issue if I was
using a BinaryReader but I’m not. I’m expecting to walk through a binary file
and not trip over any extra bytes thrown in there.

Any ideas?


Thanks,
Kyle
 
ksmith said:
I am writing a binary file using C# and then reading it using eVC++ but I am
running into a few oddities which I notice when hex editing the file created
by C#.

Here?s one thing I?ve noticed. When using the following code I would expect
the file to only contain ?(null)DEVS(null)? when it actually contains
?0x06(null)DEVS(null)?. Where?d that 0x06 come from?

It comes from the call to BinaryWriter.Write(string), as documented:

<quote>
Writes a length-prefixed string to this stream in the current encoding
of the BinaryWriter, and advances the current position of the stream in
accordance with the encoding used and the specific characters being
written to the stream.
</quote>

Note the "length-prefixed" part.

If you don't want that, you could use Encoding.GetBytes and write the
bytes directly.
 
Back
Top