问题
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, using a notation called Binary Coded Decimal.
So, I have found when outputting a NUL (0x00) [Dec 0] with a Œ (0x8C) [Dec 140] it adds an extra character  (0xC2) between them. I can't figure out why this is happening. Does anyone have any ideas? Please see my code below:
string fileName;
System.IO.StreamWriter writer;
public override void PreExecute()
{
base.PreExecute();
this.fileName = this.Variables.FilePath;
}
public override void PostExecute()
{
base.PostExecute();
writer.Flush();
writer.Close();
}
public override void Input0_ProcessInputRow(Input0Buffer Row)
{
writer.Write((char)00);
writer.Write((char)140);
writer.Write((char)13);
writer.Write((char)10);
}
Output below:
UPDATE One thing I didn't make a point of is that I am passing Hex Values into the C# Script and then writing the Characters represented by the hex value to a file with fixed length columns.
I don't know if this makes a difference, but I will also be writing other things to the file that aren't the packed values on the same lines as the packed values, and thus the reason for using the StreamWriter.
回答1:
It's an encoding issue. It shouldn't happen if you write *byte*s.
BinaryWriter writer = new BinaryWriter(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?
回答2:
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 bytesFileStream
is aStream
that reads and writes to a fileBinaryWriter
allows you to write primitive types in binary form to aStream
TextWriter
is an abstract base class that allows you to write textStreamWriter
is aTextWriter
that allows you to write text to aStream
You probably should use FileStream
or BinaryWriter
on top of a FileStream
to solve your problem.
回答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
来源:https://stackoverflow.com/questions/9196104/c-sharp-script-using-streamwriter-creates-extra-character