Bart Friederichs
Bart Friederichs

Reputation: 33573

Getting a string dynamically from strings resources

I am working on a localised C#.NET application and we are using a strings.resx file to translate hardcoded strings in the application. I use the following code to extract them:

using MyNamespace.Resources

...

string someString = strings.someString;

But, now I want to be able to define the name of the string in the call, something like this:

string someString = GetString("someString");

I have been toying a little with the ResourceManager, but i can't find a way to direct it to my strings.resx file.

How do I do that?

Upvotes: 33

Views: 69574

Answers (5)

Emil
Emil

Reputation: 6932

There is much simpler way of doing this

 [NameOfyourResxfile].ResourceManager.GetString("String Name");

in your case

strings.resx.ResourceManager.GetString("someString");

Upvotes: 10

A.Dara
A.Dara

Reputation: 784

You can write a static method like this:

public static string GetResourceTitle<T>(string key)
{
  ResourceManager rm = new ResourceManager(typeof(T));
  string someString = rm.GetString(key);
  return someString;
}

And call anywhere:

var title=  GetResourceTitle<*YouResourceClass*>(key);

It is useful when you want to have a generic function to get String of any Resource file.

Upvotes: 5

skamlet
skamlet

Reputation: 691

I had the same problem using ASP.NET Core MVC and managed to solve it using

ResourceManager rm = new ResourceManager(typeof(YourResourceClass));
string someString = rm.GetString("someString");

Very similar to @Vlad's solution, but otherwise I had a MissingManifestResourceException

Upvotes: 12

Bart Friederichs
Bart Friederichs

Reputation: 33573

A little searching did the trick. I have the right ResourceManager available in my strings class:

ResourceManager rm = strings.ResourceManager;
string someString = rm.GetString("someString");

Upvotes: 53

Vlad
Vlad

Reputation: 35594

ResourceManager.GetString should do.

Stripped down example from MSDN:

ResourceManager rm = new ResourceManager("RootResourceName",
                                         typeof(SomeClass).Assembly);
string someString = rm.GetString("someString");

Upvotes: 23

Related Questions