【问题标题】:Specify encoding when reading file from Resource从 Resource 读取文件时指定编码
【发布时间】:2016-09-30 11:18:15
【问题描述】:

我有一个 UTF8 文件,已添加到 Resources.resx 中的项目中,名为 Template.txt

如果我像这样正常读取文件:

string template = File.ReadAllText(@"filepath\Template.txt", Encoding.UTF8);

一切正常。

但是,如果我这样读:

string template = Properties.Resources.Template

里面是日文字符,所以编码错误。

byte[] bytes = Encoding.Default.GetBytes(Properties.Resources.Template);
string template = Encoding.UTF8.GetString(bytes);

这仍然会给出日文字符。

有人知道原因吗?如果我在 Visual Studio 中双击 Template.txt 文件,也可以正常读取。

【问题讨论】:

  • 您可能没有在 Resources.resx 的包含中指定 UTF8,因此在转换为资源时出现了乱码。结果,没有办法让资源恢复正常。了解如何在 Resources.resx 中指定 UTF8。
  • 如果文本显示错误,则表示您没有将其存储为 Unicode。只需确保资源实际存储为 Unicode
  • 当您将文本文件嵌入为资源时,资源管理器会努力将文件嵌入为文本,这样编码就不起作用了。这就是您可以从 Template 属性中获取字符串的原因。但正如您所知,它无法确定文本文件包含 utf8。所以它猜错了并使用了系统默认的代码页,如果文本文件包含非ASCII字符就会变成乱码。用文本编辑器打开文件,记事本也可以,将其保存为utf8,以便包含BOM。

标签: c# .net


【解决方案1】:

正如 Hans Passant 在 cmets 中所说,对文件进行编码以使其包含 UTF-8 BOM(字节顺序标记)解决了该问题。

【讨论】:

    【解决方案2】:

    在VS中,选择Resources.resx文件,然后转到File > Save Resources.resx As...

    Save with Encoding... 并选择Unicode(UTF-8 without signature) - Codepage 65001OK

    【讨论】:

    • 无论出于何种原因,notepad++ 不起作用,但 notepad 起作用了。
    【解决方案3】:

    可能是 .resx 文件中描述的编码。

    使用记事本打开 .resx 文件,您会看到如下条目:

      <data name="file1" type="System.Resources.ResXFileRef, System.Windows.Forms">
        <value>..\Resources\file1.html;System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089;Windows-1252</value>
      </data>
      <data name="file2" type="System.Resources.ResXFileRef, System.Windows.Forms">
        <value>..\Resources\file2.html;System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089;utf-8</value>
      </data>
    

    您可以将 Windows-1252 更改为 utf-8 并保存。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-12-06
      • 2012-10-27
      • 1970-01-01
      • 2018-11-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多