I just can't seem to get localization to work.
I have a class library. Now I want to create resx files in there, and return some values based on the thread culture.
How can I do that?
strings.resx
.System.Threading
and System.Globalization
Run this code:
Console.WriteLine(Properties.strings.Hello);
It should print "Hello".
Now, add a new resource file, named "strings.fr.resx" (note the "fr" part; this one will contain resources in French). Add a string resource with the same name as in strings.resx, but with the value in French (Name="Hello", Value="Salut"). Now, if you run the following code, it should print Salut:
Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo("fr-FR");
Console.WriteLine(Properties.strings.Hello);
What happens is that the system will look for a resource for "fr-FR". It will not find one (since we specified "fr" in your file"). It will then fall back to checking for "fr", which it finds (and uses).
The following code, will print "Hello":
Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo("en-US");
Console.WriteLine(Properties.strings.Hello);
That is because it does not find any "en-US" resource, and also no "en" resource, so it will fall back to the default, which is the one that we added from the start.
You can create files with more specific resources if needed (for instance strings.fr-FR.resx and strings.fr-CA.resx for French in France and Canada respectively). In each such file you will need to add the resources for those strings that differ from the resource that it would fall back to. So if a text is the same in France and Canada, you can put it in strings.fr.resx, while strings that are different in Canadian french could go into strings.fr-CA.resx.
The answer could make reference to the "behind-the-scenes" plumbing that is being done by Visual Studio here: resx.designer.cs file, making the intellisense work; satellite assemblies compiled with the class library, that need to be deployed with the compiled assembly and any later projects that use it, etc... The answer is nice and simple, but it doesn't help explain where things might go wrong eg if you don't use Visual Studio.
+1 post! Rather than making files manually, try Zeta Resource Editor (zeta-resource-editor.com/index.html). It's free and helps you do these sorts of translations MUCH faster than just in VS.
Access Modifier
should be setPublic
for resource class to be generated. The class is not necesssarily in the Properties namespace, it's where you place the .resx file.Be aware that in VS 2017 resx with localization in winform is not working due to a bug (at least till version 15.4). A ticket is available: developercommunity.visualstudio.com/content/problem/63772/…
As of .NET 4.5 it is also possible to use System.Globalization.CultureInfo.DefaultThreadCurrentCulture instead of Thread.CurrentThread.CurrentUICulture so that you change the locale for the whole application instead of thread by thread