c# - 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
我究竟做错了什么?
解决方案
内存中的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 =
推荐阅读
- css - 带有 transform rotateX 的 CSS 错误有时会旋转太多
- javascript - 在 Angular 8 /9 中,我可以在 app.module.ts 中确定我的 URL 并在声明模块时使用它吗?
- xml - xsl 中的元素:模板被忽略、XML、XSL、XHTML
- python - Append 不会在 Python 中“循环”我的搜索代码
- javascript - 使用重置按钮重置表格上的数据
- getstream-io - 为什么所有活动都显示 Unknown for the User/Actor .NET Server API w/React-JS 客户端组件
- python - 变异二维列表
- r - 如何在 R 中打印 x 轴上的所有标签?
- node.js - 在 html 中使用 NodeJS 函数
- python - 使用 matplotlib 和 y twinx 打印图例时出错