Svish
Svish

Reputation: 158351

C#: How to get a resource string from a certain culture

I have a resource assembly with translated texts in various languages. Project kind of looks like this:

I can get the texts using static properties like this:

var value = FooBar.Hello;

Or by using reflection like this:

var value = resourceAssembly
      .GetType("Namespace.FooBar")
      .GetProperty("Hello")
      .GetValue(null, null) as string;

Both ways will get me the value belonging to the current UI culture of the current thread. Which is fine and totally what I would usually like.

But, is there something I can do if I explicitly want for example the Swedish value, without having to change the UI culture?

Upvotes: 28

Views: 39486

Answers (5)

Himanshu Vohra
Himanshu Vohra

Reputation: 427

Try the following code. It worked fine for me at least:

FooBar.ResourceManager.GetString("Hello", CultureInfo.GetCultureInfo("sv-SE"))

Upvotes: 30

AnthonyWJones
AnthonyWJones

Reputation: 189555

Use the second overload of GetValue:-

 .GetValue(null, BindingFlags.GetProperty, null, null, CultureInfo.GetCultureInfo("sv-SE"))

Upvotes: -1

ScottE
ScottE

Reputation: 21630

Here's some code I've used to grab a resource file by culture name - it's vb.net, but you get the idea.

Dim reader As New System.Resources.ResXResourceReader(String.Format(Server.MapPath("/App_GlobalResources/{0}.{1}.resx"), resourceFileName, culture))

And if you want to return it as a dictionary:

If reader IsNot Nothing Then
    Dim d As New Dictionary(Of String, String)
    Dim enumerator As System.Collections.IDictionaryEnumerator = reader.GetEnumerator()
    While enumerator.MoveNext
        d.Add(enumerator.Key, enumerator.Value)
    End While
    Return d
End If

Upvotes: 1

Foxfire
Foxfire

Reputation: 5765

You can manually change the culture in your resource access class. But this is somewhat unrecommended because it leads to lots of other internationalization problems.

E.g. you would have to:

  • Handle all number-formatting with the culture overloads
  • Ensure that other libraries you use have a similar mechanism that you have
  • In cases where the above is impossible (e.g. BCL) create wrappers for everything that MIGHT be culture specific (and that is a LOT of stuff).

So if at all possible change the current UI culture of the current thread.

Upvotes: 0

Konamiman
Konamiman

Reputation: 50323

You can manually change the Culture property of the FooBar class that Visual Studio generates. Or if you are directly using the ResourceManager class, you can use the overload of GetString that takes the desired culture as a parameter.

Upvotes: 22

Related Questions