首页 > 解决方案 > 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);
}

在此处输入图像描述

标签: c#.netcharacter-encodingspecial-characters

解决方案


使用时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)

推荐阅读