【问题标题】:MissingManifestResourceException is thrown when not found resource key in resource files在资源文件中找不到资源键时抛出 MissingManifestResourceException
【发布时间】:2014-01-29 11:36:09
【问题描述】:

我创建了简单的控制台应用程序来获取资源值。应用程序正在为现有资源键工作。但 MissingManifestResourceException 会因不存在的资源键而引发。请问我的代码有什么问题?资源文件的构建操作设置为嵌入式资源。

程序.cs

using Framework;

namespace ResourcesConsole
{
  class Program
  {
    static void Main(string[] args)
    {
      string resourceValue = CustomResourceManager.GetResourceValue("notExistingResourceKey");
    }
  }
}

CustomResourceManager.cs

using System.Collections.Generic;
using System.Globalization;
using System.Reflection;
using System.Resources;

namespace Framework
{
  public class CustomResourceManager
  {
    private static Dictionary<string, ResourceManager> _resourceManagerDict;

    static CustomResourceManager()
    {
      _resourceManagerDict = new Dictionary<string, ResourceManager>();

      string defaultResourceManagerName = "Framework.CustomResources";
      ResourceManager defaultResourceManager = new System.Resources.ResourceManager(defaultResourceManagerName, Assembly.GetExecutingAssembly());

      _resourceManagerDict.Add(defaultResourceManagerName, defaultResourceManager);
    }

    public static string GetResourceValue(string key, string language = "en")
    {
      CultureInfo culture = new CultureInfo(language);

      string value = null;

      foreach (var resourceManager in _resourceManagerDict)
      {
        value = resourceManager.Value.GetString(key, culture); // MissingManifestResourceException is thrown when resource key is not found in resource file (should return null)

        if (value != null)
          return value;
      }

      return key;
    }
  }
}

【问题讨论】:

  • 神秘问题。当您使用不存在的资源时,您还期望发生什么?
  • GetString 方法应该返回 null 根据文档 msdn.microsoft.com/cs-cz/library/bsb0cfet(v=vs.110).aspx
  • 这不是异常告诉你的。找不到整个资源块。您将错误的参数传递给 ResourceManager 构造函数。通过运行 ildasm.exe 并查看清单中的 .mresource 指令来仔细检查流名称。
  • ResourceManager 构造函数的参数是正确的。我可以获得现有密钥的资源价值。
  • 我的水晶球说您实际上是在向该字典添加多个资源管理器。其中一个是坏的,因此产生了异常。嗯,不太确定它是否正确,它从那个猜测中产生了一个相当讨厌的裂缝。唉,今天没打算去购物。

标签: c# embedded-resource resourcemanager


【解决方案1】:

我找到了解决方案。问题是我缺少不变(或默认)文化的资源文件。所以我将 CustomeResources.en.resx 重命名为 CustomeResources.resx,它工作正常

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多