C # Script Using StreamWriter creates an extra character?

I am using C # Script Tasks in SSIS to output ASCII characters. I do this because I create a file with Packed fields, a packed field takes two digits per byte using the Binary Coded Decimal notation.

So, I found that when outputting NUL (0x00) [Dec 0] with Ε’ (0x8C) [Dec 140], it adds an extra character Γ‚ (0xC2) between them. I can’t understand why this is happening. Does anyone have any ideas? 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); } 

The result is below:

Extracharacter

UPDATE The only thing I did not talk about is that I pass Hex Values ​​to C # Script, and then write the characters represented by the hexadecimal value into a file with fixed-length columns.

I don't know if this matters, but I will also write other things to the file that are not packed values ​​on the same lines as packed values, and therefore the reason for using StreamWriter.

+1
source share
3 answers

This is an encoding problem. This should not happen if you write * byte * s.

 BinaryWriter writer = new BinaryWriter(someStream); write.Write((byte)123); // just an example! not a "that how you should do it" 

The best solution would be to choose the right coding. But does your character really matter in the file?

+1
source

A StreamWriter is for writing text to a stream. It always uses encoding, and if you do not specify it when creating it, it will use UTF-8 (unsigned byte order - specification). You get a UTF-8 code that tries to translate text (as single characters) into UTF-8.

If you want to write bytes to a stream, simply write to the stream directly using the Write method, which takes an array of bytes. If you want to write to a file, you can create a FileStream and use it as a stream.

Naming classes in the System.IO namespace can be confusing from time to time:

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

You should probably use FileStream or BinaryWriter on top of FileStream to solve your problem.

+3
source
+1
source

Source: https://habr.com/ru/post/1393281/


All Articles