Tim*_*Tim 16 c# utf-8 iso-8859-1 latin1
我正在发送以ISO 88591-1格式保存的文本文件,其中包含来自Latin-1范围的重音字符(以及普通的ASCII az等).如何使用C#将这些文件转换为UTF-8,以便ISO 8859-1中的单字节重音字符成为有效的UTF-8字符?
我尝试使用带有ASCIIEncoding的StreamReader,然后通过实例化编码ascii和编码utf8然后使用Encoding.Convert(ascii, utf8, ascii.GetBytes( asciiString) )- 将ASCII字符串转换为UTF-8,但重音字符被渲染为问号.
我错过了什么步骤?
Ada*_*son 34
你需要得到适当的Encoding对象.ASCII就像它的名字一样: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());
}
}
Run Code Online (Sandbox Code Playgroud)
但是,如果你想自己拥有字节数组,那就很容易了Encoding.Convert.
byte[] converted = Encoding.Convert(Encoding.GetEncoding("iso-8859-1"),
Encoding.UTF8, data);
Run Code Online (Sandbox Code Playgroud)
但这里要注意的是,如果你想要走这条路,那么你应该是很重要的不是使用基于编码字符串读者喜欢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);
}
}
Run Code Online (Sandbox Code Playgroud)
在此示例中,buffer变量将作为a填充文件中的实际数据byte[],因此不会进行任何转换.Encoding.Convert指定源和目标编码,然后将转换后的字节存储在名为...的变量中converted.然后将其直接写入输出文件.
就像我说的,第一个选项使用StreamReader,并StreamWriter会简单得多,如果这是你在做什么,但后者的例子应该给你更多的是暗示的,以什么实际发生的.
Han*_*ant 13
如果文件相对较小(例如,~10兆字节),则只需要两行代码:
string txt = System.IO.File.ReadAllText(inpPath, Encoding.GetEncoding("iso-8859-1"));
System.IO.File.WriteAllText(outPath, txt);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
47035 次 |
| 最近记录: |