Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Strongly type resource files in C#

I have a windows application that accesses a file in a class library project.

public static class Global
{
    private static ResourceManager ResourceManager { get; set; }

    static Global ()
    {
        ResourceManager = new ResourceManager("MyClassLibraryProject.Resource", Assembly.GetExecutingAssembly());
    }

    private static string GetValue (string name)
    {
        return (ResourceManager.GetString(name, Options.CultureInfo));
    }

    public static string ProductName
    {
        get
        {
            return (GetValue(MethodBase.GetCurrentMethod().Name.Replace("get_", "")));
        }
    }
}
`

I have created the ProductName property manually in this example. Is there an easier way to access strongly-typed names for each row in the resource file?

like image 337
Raheel Khan Avatar asked Apr 18 '12 11:04

Raheel Khan


1 Answers

This might do what you're looking for: https://docs.microsoft.com/en-us/dotnet/framework/tools/resgen-exe-resource-file-generator

Since resource property types are determined at runtime, you'll need a tool to analyse the resource file pre-compile time and generate the wanted properties. Resgen.exe will do this, but you could create a custom t4 script or something else as well.

From the docs:

The following command reads an XML-based input file myResources.resx and writes a binary resources file named myResources.resources. It also generates a C# file named MyFile.cs with a class named MyClass that contains strongly-typed properties that match the resources that are referenced in the input file. The MyClass class is contained within a namespace named Namespace1.

resgen myResources.resx myResources.resources /str:C#,Namespace1,MyClass,MyFile.cs

like image 101
Michael Sondergaard Avatar answered Oct 11 '22 11:10

Michael Sondergaard