c# - C# 外来字符处理
问题描述
我正在尝试读取文件,然后以另一种格式写入。我的文本中有一些葡萄牙语字符被损坏或问号。
我有一个我们正在阅读的示例文本:
PZO DISPONIVEL PARA VENDA CDB PàS P SNA
string[] lines = System.IO.File.ReadAllLines(@"C:\test_pcharacters.txt");
// Display the file contents by using a foreach loop.
System.Console.WriteLine("Contents of WriteLines2.txt = ");
foreach (string line in lines)
{
Encoding iso = Encoding.GetEncoding("ISO-8859-9");
Encoding utf8 = Encoding.UTF8;
byte[] utfBytes = utf8.GetBytes(line);
byte[] isoBytes = Encoding.Convert(utf8, iso, utfBytes);
string msg = iso.GetString(isoBytes);
// Use a tab to indent each line of the file.
Console.WriteLine("\t" + msg);
Console.WriteLine("\t" + line);
}
解决方案
使用时File.ReadAllines
,如果未Encoding
指定具体内容,则该函数将默认为 UTF8。
在您的情况下,明确指定默认编码(Encoding.Default
)将解决问题:
string[] lines = System.IO.File.ReadAllLines(@"C:\users\mparkin\desktop\test_pcharacters.txt", Encoding.Default);
默认编码使用运行软件的当前代码页。这很可能(但不能保证)是 Windows-1252,其中包括 ANSI 字符(例如您在文本文件中的字符)。
输出:
Contents of WriteLines2.txt =
PZO DISPONIVEL PARA VENDA CDB PàS P SNA
PZO DISPONIVEL PARA VENDA CDB PàS P SNA
正如@DmitryBychenko 所指出的,依赖 Encoding.Default 可能很危险,因为返回的编码可能因环境而异。
作为替代方案,您可以指定用于生成文件的确切代码页。在 Windows 上,此代码为 1252,您可以使用以下方法获取:
Encoding.GetEncoding(1252)
推荐阅读
- reactjs - redux-saga 总是返回 'undefined'
- javascript - 如何使用 javascript 淡入淡出
- cakephp - cakephp 3 补丁存储额外的列数据
- r - 如何在 R 中编写循环以根据列名创建多个不同的数据子集?
- java - AnysoftKeyboard (Android) 的构建问题
- bash - LDAP 转储的 Bash 脚本数据解析
- python - 用 Scrapy 和 Selenium 抓取 CNN
- pine-script - 每次出现新栏时标签都会重复
- php - 无法在本地 Apache 服务器中打开 PHP webapp。获取错误 404
- python - Keras 创建新的损失函数