C# Script Using Streamwriter Creates Extra Character?
Solution 1:
A StreamWriter is for writing text to a stream. It always uses an encoding and if you don't specify one when you create it it will use UTF-8 (without a byte order mark - BOM). The output you get is the UTF-8 encoder trying to translate the the text (in the form of individual characters) into UTF-8.
If you want to write bytes to a stream simply write to the stream directly using the Write method that accepts an array of bytes. If you want to write to a file you can create a FileStream and use that as the stream.
The naming of classes within the System.IO namespace can be confusing at times:
Streamis an abstract base class providing methods to read and write bytesFileStreamis aStreamthat reads and writes to a fileBinaryWriterallows you to write primitive types in binary form to aStreamTextWriteris an abstract base class that allows you to write textStreamWriteris aTextWriterthat allows you to write text to aStream
You probably should use FileStream or BinaryWriter on top of a FileStream to solve your problem.
Solution 2:
It's an encoding issue. It shouldn't happen if you write *byte*s.
BinaryWriterwriter=newBinaryWriter(someStream);
write.Write((byte)123); // just an example! not a "that's how you should do it"A better solution would be to select the proper encoding. But does the way your characters look in the file really matter?
Solution 3:
You must have not specified the correct encoding of your writer.
See: http://msdn.microsoft.com/en-us/library/72d9f8d5.aspx
and: http://msdn.microsoft.com/en-us/library/system.text.encoding.aspx
Post a Comment for "C# Script Using Streamwriter Creates Extra Character?"