0
votes

I want to convert string values from array in some way (described below) and save character to file.

Conversion from ... to:

  1. I have string[,,] array with hex values (exactly saved - for example value 1A is saved as "1A")
  2. I convert each cell to int value
  3. Convert int value to char
  4. Save character to file using StreamWriter

The code:

StreamWriter streamWriter = new StreamWriter(this.outputFilePath);

for (int i = 0; i < this.workingArray.GetLength(0); i++)
{
    for (int j = 0; j < this.workingArray.GetLength(1); j++)
    {
        for (int k = 0; k < this.workingArray.GetLength(2); k++)
        {
            int value = int.Parse(this.workingArray[i, j, k], System.Globalization.NumberStyles.HexNumber);
            char symbol = Convert.ToChar(value);

            streamWriter.Write(symbol);
        }
    }
}
streamWriter.Close();

The problem is, when my workingArray cell value is FE, I obtain value CE in file. I don't know why it saves values in wrong way. Moreover, symbol code is 254, and after hex conversion it is exactly FE, but in the output file it's value is wrong.

Is there any solution for this problem?

2

2 Answers

3
votes

Just use FileStream:

FileStream binaryWriter = new FileStream(this.outputFilePath, FileMode.Create,FileAccess.ReadWrite);
//some code here
binaryWriter.WriteByte(0xFE);
//some code here
binaryWriter.Close();
1
votes

Your stream writer is persisting the char using UTF-8. It will write two bytes for your single char.

To change this, you need to instruct the StreamWriter to use a different encoding.