Skip to content Skip to sidebar Skip to footer

C# Script Using Streamwriter Creates Extra Character?

I am using a C# Script Tasks in SSIS to output ASCII characters. I am doing this because I am creating a file with Packed fields, a packed field takes two digits into each byte, us

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:

  • Stream is an abstract base class providing methods to read and write bytes
  • FileStream is a Stream that reads and writes to a file
  • BinaryWriter allows you to write primitive types in binary form to a Stream
  • TextWriter is an abstract base class that allows you to write text
  • StreamWriter is a TextWriter that allows you to write text to a Stream

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:

Post a Comment for "C# Script Using Streamwriter Creates Extra Character?"