Initialize ResourceManager dynamically

夙愿已清 提交于 2019-11-28 05:57:49

问题


I have this function and it works fine to get a translated value from this specific resource file called OkayMessages.

public static string GetResourceString(string resourceKey){
  ResourceManager resourceManager = Resources.OkayMessages.ResourceManager;
  return resourceManager.GetString(resourceKey);
}

But i have more than 1 resource file and i want this function to get values from those files as well.. Only, i'm having trouble with dynamically/programmatically selecting the right resource(manager). I have tried to use the code below, and some variants to that, but i always get an error.

public static string GetResourceString(string resourceFile, string resourceKey){
  ResourceManager resourceManager = new System.Resources.ResourceManager("Resources." + resourceFile, Assembly.GetExecutingAssembly());
  return resourceManager.GetString(resourceKey);
}

The error i got most of the times was: Could not find any resources appropriate for the specified culture or the neutral culture. Make sure "Resources.OkayMessages.resources" was correctly embedded or linked into assembly..

Update: I'm using the \App_GlobalResources\ folder for my resource files, and it seems that this is the problem. When i place a resource file in the root of my project, i can initialize a ResourceManager without problems.


回答1:


After searching in the wrong direction for a while, I just found the most simple answer to this problem. It turns out that there is a method called GetGlobalResourceObject.

So in my case I'm now using this line of code which does all:

GetGlobalResourceObject("OkayMessages", "PasswordChanged").ToString();



回答2:


Read carefully this article and you'll find that you need to specify correct namespace of the resource. That's your problem. Here is working example if OkayResources.resx resides in project root folder:

using System.Reflection;
using System.Resources;
using System.Web.UI;

namespace WebApplication1
{
    public partial class _Default : Page
    {

        public _Default()
        {
            var result = GetResourceString("OkayResources", "SomeKey");
        }

        private static string GetResourceString(string resourceFileName, string key)
        {
            var resourceName = "WebApplication1." + resourceFileName;
            var resourceManager = new ResourceManager(resourceName, Assembly.GetExecutingAssembly());
            return resourceManager.GetString(key);
        }
    }
}

If you put your resource file into Resources folder you'll have to update resource namespace:

var resourceName = "WebApplication1.Resources." + resourceFileName;


来源:https://stackoverflow.com/questions/11181211/initialize-resourcemanager-dynamically

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!