Czechtim
Czechtim

Reputation: 51

MissingManifestResourceException is thrown when not found resource key in resource files

I created easy console application for getting resource values. Application is working for existing resource keys. But MissingManifestResourceException is thrown for not existing resourceKeys. What is wrong with my code please? Build action at resource files is set to 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

Upvotes: 1

Views: 1150

Answers (1)

Czechtim
Czechtim

Reputation: 51

I found the solution. Problem was that I was missing resource file for invariant (or default) culture. So I renamed CustomeResources.en.resx to CustomeResources.resx and it works fine

Upvotes: 1

Related Questions