你需要获取正确的编码
对象。ASCII正如其名称所示,意味着它只支持7位ASCII字符。如果你想要做的是转换文件,则这可能比直接处理字节数组更容易。
using (System.IO.StreamReader reader = new System.IO.StreamReader(fileName,
Encoding.GetEncoding("iso-8859-1")))
{
using (System.IO.StreamWriter writer = new System.IO.StreamWriter(
outFileName, Encoding.UTF8))
{
writer.Write(reader.ReadToEnd());
}
}
然而,如果你想要字节数组本身,可以使用Encoding.Convert
轻松实现。
byte[] converted = Encoding.Convert(Encoding.GetEncoding("iso-8859-1"),
Encoding.UTF8, data)
需要注意的是,如果你想采用这种方法,那么不应该使用基于编码的字符串读取器,例如StreamReader
进行文件IO操作。更适合的是使用FileStream
,因为它将读取文件的实际字节。
为了完全探讨这个问题,可以尝试以下代码:
using (System.IO.FileStream input = new System.IO.FileStream(fileName,
System.IO.FileMode.Open,
System.IO.FileAccess.Read))
{
byte[] buffer = new byte[input.Length];
int readLength = 0;
while (readLength < buffer.Length)
readLength += input.Read(buffer, readLength, buffer.Length - readLength);
byte[] converted = Encoding.Convert(Encoding.GetEncoding("iso-8859-1"),
Encoding.UTF8, buffer);
using (System.IO.FileStream output = new System.IO.FileStream(outFileName,
System.IO.FileMode.Create,
System.IO.FileAccess.Write))
{
output.Write(converted, 0, converted.Length);
}
}
在这个例子中,变量
buffer
会被实际文件数据以
byte[]
的形式填充,因此不需要进行任何转换。
Encoding.Convert
指定源编码和目标编码,然后将转换后的字节存储在名为
converted
的变量中。然后,它直接写入输出文件中。
正如我所说的,如果这就是你要做的全部内容,使用
StreamReader
和
StreamWriter
的第一种选项会更简单,但后一个示例应该更能让你了解实际上正在发生什么。