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:
- 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 w开发者_如何学编程ays 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?
Try the following code. It worked fine for me at least:
FooBar.ResourceManager.GetString("Hello", CultureInfo.GetCultureInfo("sv-SE"))
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.
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
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.
Use the second overload of GetValue:-
.GetValue(null, BindingFlags.GetProperty, null, null, CultureInfo.GetCultureInfo("sv-SE"))
精彩评论