【问题标题】:Unable to convert special characters in UTF-8 file into ANSI无法将 UTF-8 文件中的特殊字符转换为 ANSI
【发布时间】:2020-04-13 11:23:05
【问题描述】:

我有一个需要读取的文件,并且必须在末尾添加一个文本。 程序因字符 "í" 而失败。 在以记事本++(UTF-8)编码打开文件时,我可以看到

在我的 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/,确实学到了很多,但还是无法解决问题。

我得到了什么:

我需要什么:

On Microsoft website:

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

【问题讨论】:

    标签: c# utf-8 ansi


    【解决方案1】:

    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。

    附:另请注意,StreamWriter 中的 false 不会追加到末尾,but overwrite

    【讨论】:

    • 非常感谢@user2316116 这个解决方案有效!!!是的,我将使用 'true' 来附加文本。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-30
    • 2021-10-24
    • 1970-01-01
    • 2018-05-24
    相关资源
    最近更新 更多