[英]C# int to char conversion in streamwriter
I want to convert string values from array in some way (described below) and save character to file. 我想以某种方式(如下所述)从数组转换字符串值并将字符保存到文件。
Conversion from ... to: 从...转换为:
StreamWriter
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. 问题是,当我的
workingArray
单元值为FE时,我在文件中获得了值CE。 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.
此外,符号代码为254,十六进制转换后为精确FE,但在输出文件中其值为错误。
Is there any solution for this problem? 这个问题有什么解决办法吗?
Just use FileStream: 只需使用FileStream:
FileStream binaryWriter = new FileStream(this.outputFilePath, FileMode.Create,FileAccess.ReadWrite);
//some code here
binaryWriter.WriteByte(0xFE);
//some code here
binaryWriter.Close();
Your stream writer is persisting the char using UTF-8. 您的流作家正在使用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. 要更改此设置,您需要指示
StreamWriter
使用其他编码。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.