首页 > 解决方案 > c#将编码1252转换为1251

问题描述

尝试将编码 cp 1252 的文本转换为 cp 1251。这段代码效果很好。

var bytes = Encoding.GetEncoding(1252).GetBytes(textBox1.Text);
textBox2.Text = Encoding.GetEncoding(1251).GetString(bytes);

但是对于大文件,这并不容易。所以我尝试使用文件流。如果我尝试读取文件-> 转换为字节-> 写入。它是行不通的。添加 Encodig.GetEncoding(1252) 读取和 Encoding.GetEncoding(1251) 写入没有帮助。

 string file_data = System.IO.File.ReadAllText(path);
 var bytes = Encoding.GetEncoding(1252).GetBytes(file_data);
 string file_data_in_1251 = Encoding.GetEncoding(1251).GetString(bytes);
 System.IO.File.WriteAllText(path + "_1251", file_data_in_1251);

如果我以字节为单位读取文件...

byte[] allData = File.ReadAllBytes(path);
string file_data_in_1251 = Encoding.GetEncoding(1251).GetString(allData);
System.IO.File.WriteAllText(path + "_1251", file_data_in_1251, Encoding.GetEncoding(1251));

它适用,但不适用于所有文件。第一个代码适用于所有文件。

我比较了从文本到字节的字节数据和从文件到字节的数据,它的不同!

文本

[0] 32  byte
[1] 60  byte
[2] 32  byte
[3] 116 byte
[4] 97  byte
[5] 103 byte
[6] 32  byte
[7] 107 byte
[8] 32  byte
[9] 61  byte

文件

[0] 32  byte
[1] 60  byte
[2] 116 byte
[3] 97  byte
[4] 103 byte
[5] 32  byte
[6] 107 byte
[7] 61  byte
[8] 39  byte
[9] 78  byte

我究竟做错了什么?

标签: c#encoding

解决方案


内存中的Astring存储为UTF16,因此您的程序当前正在执行以下步骤:

// let C# guess the encoding of the file and convert to UTF16
string file_data = System.IO.File.ReadAllText(path);

// get a byte array of that string in 1252 encoding
var bytes = Encoding.GetEncoding(1252).GetBytes(file_data);

// pretend the 1252 encoded data is actually 1251 encoded and convert to UTF16
string file_data_in_1251 = Encoding.GetEncoding(1251).GetString(bytes);

// let C# decide what encoding to use when writing the file
System.IO.File.WriteAllText(path + "_1251", file_data_in_1251);

正如 Igor 建议的那样,您可以向ReadAllText方法提供编码以告诉 C# 文件当前编码为什么,并WriteAllText指示要写入的编码。

因此,以下方法可以解决问题:

string file_data = System.IO.File.ReadAllText(path, Encoding.GetEncoding(1252));
System.IO.File.WriteAllText(path + "_1251", file_data, Encoding.GetEncoding(1251));

我在控制台应用程序中尝试了以下代码来测试它:

string t = "háéó < tag k =";
File.WriteAllText(@"c:\temp\1.tmp", t, Encoding.GetEncoding(1252));
string read = File.ReadAllText(@"c:\temp\1.tmp", Encoding.GetEncoding(1252));
File.WriteAllText(@"c:\temp\2.tmp", read, Encoding.GetEncoding(1251));

结果文件包含:

haeo <标签k =


推荐阅读