【问题标题】:File created with File.CreateText() are not in UTF-8使用 File.CreateText() 创建的文件不是 UTF-8
【发布时间】:2018-12-21 05:22:09
【问题描述】:

File.CreateText() 的文档说“创建或打开一个文件以写入 UTF-8 编码文本。”

但是,创建的文件是用西欧编码的。

String template = File.ReadAllText(Settings.Default.template, Encoding.UTF8);
template = template.Replace("{{content}}", "éèê");
using (StreamWriter sw = File.CreateText(item_path))
{
   sw.Write(template);
}

我使用此代码生成带有<meta charset="UTF-8"> 的HTML 页面,但重音字母无法正确显示,除非我手动将浏览器的编码设置更改为“西欧”。

知道为什么这些文件不是 UTF-8 格式吗?

【问题讨论】:

  • 我认为我要做的第一件事是直接在功能强大的文本编辑器中打开文件并检查编码,而不是依赖浏览器告诉我的任何内容
  • @CaiusJard 我做到了。 notepad++ 显示“ANSI”而不是 UTF-8。如果我使用 notepad++ 的转换为 UTF-8 功能,生成的文件在浏览器中运行良好。
  • 您的测试可能有问题。请edit您的问题提供更多详细信息,说明您如何断定文件的字节不是字符“éèê”的UTF-8编码。

标签: c# utf-8 character-encoding


【解决方案1】:

我无法重现您的问题,这是我用来生成一堆低端 utf8 字符并将它们写入文件的代码:

        StringBuilder sb = new StringBuilder();
        for (int i = 1; i < 1025; i++)
        {
            sb.Append((char)i);
        }

        string fn = Path.GetTempFileName();
        using (var sw = File.CreateText(fn))
        {
            sw.Write(sb.ToString());
            sw.Flush();
            sw.Close();
        }
        Process.Start(Path.GetDirectoryName(fn));

以下是我在 notepad++ 中打开时看到的内容:

如果你这样做,你会得到什么?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-12
    • 2015-07-15
    • 2013-12-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多