无法将UTF-8文件中的特殊字符转换为ANSI

问题描述 投票:0回答:1

我有一个需要读取的文件,并且必须在最后添加一个文本。程序由于字符“í”而失败。以notepad ++(UTF-8)编码打开文件时,我可以看到enter image description here

在我的C#代码中,我尝试将其转换为默认编码,但是应用程序将其更改为“?”而不是“í”。

示例代码:

string processFilePath = @"D:\Test\File1.txt";
string outfile = @"D:\Test\File2.txt";

using (StreamReader reader = new StreamReader(processFilePath))
{
    using (StreamWriter writer = new StreamWriter(outfile, false, Encoding.Default))
    {
        writer.WriteLine(reader.ReadToEnd());
    }
}

我在SO上调查了类似的问题(上面的代码片段是这里的修改版):UTF-8 to ANSI Conversion using C#

我尝试了“ System.Text.Encoding”中提供的不同类型的编码-ASCII / UTF * /默认值,但我能得到的最好的是“?”而不是“í”。

我也经历过:http://kunststube.net/encoding/,我确实学到了很多东西,但是仍然无法解决问题。

我得到的是:enter image description here

我需要:enter image description here

[On Microsoft websiteenter image description here

我还缺少什么(如果存在System.Text.Encoding.ANSI,应该很容易)

c# utf-8 ansi
1个回答
0
投票

MSDN

除非另有说明,否则StreamReader默认为UTF-8编码,而不是默认使用当前系统的ANSI代码页。

即当打开StreamReader(processFilePath)时,它会像UTF-8那样获取数据,情况似乎并非如此,即,如果源文本是ANSI,或者很可能是Windows-1252(西班牙语),请使用

using (StreamReader reader = new StreamReader(processFilePath, Encoding.GetEncoding(1252)))
{
    using (StreamWriter writer = new StreamWriter(outfile, false, Encoding.UTF8))
    {
        writer.WriteLine(reader.ReadToEnd());
    }
} 

请注意指定了1252和UTF8。

P.S。另请注意,StreamWriter中的false不会追加到末尾but overwrite

© www.soinside.com 2019 - 2024. All rights reserved.