Search code examples
embedded-resourcecultureinfoc#

Using resource files (CultureInfo) in C# class file


I need a help with using resource files in C# class files.

My code:

class errorMessages
{
    private static ResourceManager LocRM = new ResourceManager("Project1.languageFile", typeof(errorMessages).Assembly);

    public static void XMLParseError(String msg)
    {
        MessageBox.Show(LocRM.GetString("XMLParseError") + "\n" + msg, LocRM.GetString("error"), 
        MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1);
    }
}

+ created 2 .resx files named languageFile.en.resx and languageFile.pl-PL.resx in main Project1 folder

Now I want to use String from languageFile, in my class errorMessages, specified to localization which was set before. How can I do it?

I tried to add my Strings to WinForm .resx file, but that's clearing my data with any edit of WinForm.


Solution

  • I found answer for my question by myself, so I will write that solution, I hope it will help somebody.

    Default resources file is located in [projectName]/Properties. I you want to add manually localizable resource files, you need to do that this way:

    right click on Project in Solution Explorer -> Add new item -> resource file

    Then set the name of file to Resources.[language].resx - in my case that are two files, Resources.pl-PL.resx and Resources.en.resx. After file is created, move it to Properties directory.

    Now you can add your resources and use it this way:

    MessageBox.Show(Project1.Properties.Resources.XMLParseError, Project1.Properties.Resources.information,
    MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1);
    

    Now chosen String will be in language setted in CultureInfo, or, if there is no that resource, default Resource file will be used.

    source: MSDN - How to: Create a Localized Version of a Resource File