Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Localization/Resource files in Class Library

I am trying to achieve globalization in a .NET class library. In a .NET web application this seems to work fine. I can add multiple resource files under the App_GlobalResources.

e.g.

LocalizedText.resx
LocalizedText.fr.resx

However resource files are handled differently in Class Libraries. I add a resource file by
1) Opening the Properties for the Class Library
2) Clicking on the Resources Tab
3) Clicking on the link to create a “default resources file”

With this model it seems to only want to allow one default resources file. I can rename files and seem to get around this “one file” limitation but if I produce resource files with the same names as above there appears to be no code generated for the “LocalizedText.fr.resx” file. If I reference a string in code like so…

myControl.Text = Properties.LocalizedText.MyLocalizedText;

It references the LocalizedText.resx file for the value (ignoring the fact that I have the culture set to French). I’m guessing that whatever auto-generates the code for the designer file sees that there is already a “LocalizedText” class and doesn’t generate the necessary code.

Is there not a way (equivalent to the web application project) that I can use multiple resource files in a Class Library, named differently for each culture, and be able to easily access this in code (trusting .NET to switch appropriately depending on the culture info)?

Many Thanks

like image 490
user3482367 Avatar asked Nov 10 '22 04:11

user3482367


1 Answers

First: create a folder in your project named 'MyFolder'.

Second: add a resource file named 'MyResourceFile' to the folder.

Third: where you want access the resource values, import:

using System.Reflection;
using System.Resources;
using MyProject.MyFolder.MyResourceFile;

and create a property that can access the your resource. Like this:

public static ResourceManager oResourceManager = new ResourceManager("MyProject.MyFolder.MyResourceFile", typeof(MyResourceFile).Assembly);

Fourth: Get the data from your property:

oResourceManager.GetString("ResourceKey", System.Globalization.CultureInfo.CurrentCulture);
like image 128
Kane Avatar answered Nov 15 '22 05:11

Kane