Search code examples
c#.netfile-iobinarywriter

BinaryWriter puts dirty chars at the begin writing in AppendMode


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

The issue occurs during the execution of a NTService which writes many reports on a file. This is the simple code I used:

 FileStream fsw = new FileStream(fileName, FileMode.Append, FileAccess.Write, FileShare.Write);
            BinaryWriter w = new BinaryWriter(fsw);
            w.Write(report);
            w.Flush();
            fsw.Flush();
            w.Close();
            fsw.Close();

The output is properly flushed in the file, but at the begin of every write two strange character appears (�). I deploy the service on several machines and the problem persist.

Thanks in advance for your help.


Solution

  • Try this:

        BinaryWriter w = new BinaryWriter(fsw);
    
        w.Write(UTF8Encoding.Default.GetBytes(report));