Search code examples
c#globalization

Resource Globalization using C# - Label and Error message


I have implemented globalization using RESX files in my winform project using the .NET C# 4.7.2 framework. The current RESX files are used for Labels, now I need to have another resource file for Error messages.

I'm not sure how can I create different resource files "ABC.Error.Resources.cs-CZ.resx" and "ABC.Label.Resources.cs-CZ.resx" in the same project, as the resource DLL's are created for the respective language labels only.

My Solution structure is:

--Solution.sln
---Project.proj
----Resources(folder containing label resource files)
-----ABC.Label.Resources.cs-CZ.resx

Any help is appreciated


Solution

  • Found two approaches to solve above-mentioned problem.

    • approach 1

    using "CreateFileBasedResourceManager" from "ResourceManager" class of .NET framework

    step 1: Convert ".RESX" file to ".resources" file using "resgen.exe" from .NET framework.

    resgen

    Step 2: use below method to get the data from the resources file

    static string ReadResourceValue(string file, string key)
    
            {
    
                string resourceValue = string.Empty;
                try
                {
    
                    string resourceFile = file;
    
                    string filePath =  "ConsoleApp1.en-GB.resources";
    
                    ResourceManager resourceManager = ResourceManager.CreateFileBasedResourceManager(resourceFile, filePath, null);
                    // retrieve the value of the specified key
                    CultureInfo ci = new CultureInfo("en-IN");
                    resourceValue = resourceManager.GetString(key, ci);
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                    resourceValue = string.Empty;
                }
                return resourceValue;
            }
    
    • approach 2

    using "ResXResourceSet" from System.Resources class of .NET framework.

    static string ReadResourceFromFile()
            {
                string resxFile = "Resources\ConsoleApp1.en-GB.resx";
                string retValue = string.Empty;
                using (ResXResourceSet resxSet = new ResXResourceSet(resxFile))
                {
                    // Retrieve the string resource for the title.
                    retValue = resxSet.GetString("Test1");
                }
                return retValue;
            }
    

    Hope this will help someone in future.