Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic reference to resource files in C#

I have an application on which I am implementing localization.

I now need to dynamically reference a name in the resouce file.

assume I have a resource file called Login.resx, an a number of strings: foo="hello", bar="cruel" and baz="world"

normally, I will refer as: String result =Login.foo; and result=="hello";

my problem is, that at code time, I do not know if I want to refer to foo, bar or baz - I have a string that contains either "foo", "bar" or "baz".

I need something like:

Login["foo"];

Does anyone know if there is any way to dynamically reference a string in a resource file?

like image 812
Joda Avatar asked Aug 27 '08 10:08

Joda


2 Answers

You'll need to instance a ResourceManager for the Login.resx:

var resman = new System.Resources.ResourceManager(
    "RootNamespace.Login",
    System.Reflection.Assembly.GetExecutingAssembly()
)
var text = resman.GetString("resname");

It might help to look at the generated code in the code-behind files of the resource files that are created by the IDE. These files basically contain readonly properties for each resource that makes a query to an internal resource manager.

like image 77
Konrad Rudolph Avatar answered Sep 20 '22 15:09

Konrad Rudolph


If you put your Resource file in the App_GlobalResources folder like I did, you need to use

global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("RootNamespace.Login", global::System.Reflection.Assembly.Load("App_GlobalResources"));

It took me a while to figure this out. Hope this will help someone. :)

like image 36
StarCub Avatar answered Sep 21 '22 15:09

StarCub