Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
942 views
in Technique[技术] by (71.8m points)

asp.net - Initialize ResourceManager dynamically

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...