资源文件中找不到资源键时抛出MissingManifestResourceException

时间:2014-01-29 11:36:09

标签: c# embedded-resource resourcemanager

我创建了简单的控制台应用程序来获取资源值。应用程序正在为现有资源键工作。但是,对于不存在的resourceKeys,抛出了MissingManifestResourceException。我的代码有什么问题吗?资源文件的构建操作设置为Embedded Resource。

Program.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;
    }
  }
}

Solution

1 个答案:

答案 0 :(得分:1)

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