Why does BinaryWriter prepend gibberish to the start of a stream? How do you avoid it?

They are not byte-order marks but a length-prefix, according to MSDN:

public virtual void Write(string value);

Writes a length-prefixed string to
[the] stream

And you will need that length-prefix if you ever want to read the string back from that point. See BinaryReader.ReadString().

Additional

Since it seems you actually want a File-Header checker

  1. Is it a problem? You read the length-prefix back so as a type-check on the File it works OK

  2. You can convert the string to a byte[] array, probably using Encoding.ASCII. But hen you have to either use a fixed (implied) length or… prefix it yourself. After reading the byte[] you can convert it to a string again.

  3. If you had a lot of text to write you could even attach a TextWriter to the same stream. But be careful, the Writers want to close their streams. I wouldn’t advice this in general, but it is good to know. Here too you will have to mark a Point where the other reader can take over (fixed header works OK).

Leave a Comment