views:

779

answers:

4

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

  • FooBar.resx
  • FooBar.nb-NO.resx
  • FooBar.sv-SE.resx
  • ...

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?

+2  A: 

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.

Konamiman
Can ResourceManagers be created and thrown away easily, or do they require clean up and/or should they be only created once and used for much?
Svish
Ended up using ResourceManagers :)
Svish
A: 

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.

Foxfire
A: 

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
ScottE
A: 

Use the second overload of GetValue:-

 .GetValue(null, BindingFlags.GetProperty, null, null, CultureInfo.GetCultureInfo("sv-SE"))
AnthonyWJones
Hm... I tried this, but it just seemed to return the same value. Will have to try again...
Svish
I guess it would depend on how the property is implemented, you don't actually show the property implementation.
AnthonyWJones
That's because I haven't implemented it. It's just the default visual studio generated stuff.
Svish
Couldn't figure out how to get it to work, so ended up using ResourceManagers. Really wish I could've just used that GetValue overload though. Oh well...
Svish