microsoft / dotnet

This repo is the official home of .NET on GitHub. It's a great starting point to find many .NET OSS projects from Microsoft and the community, including many that are part of the .NET Foundation.
https://devblogs.microsoft.com/dotnet/
MIT License
14.25k stars 2.2k forks source link

Question: Read Resx Files from a project in .NET 7/8 at design time. #1395

Open chassq opened 11 months ago

chassq commented 11 months ago

We wanted to try and figure out which NuGet package to install to allow us to read resx (resource files in resx format) from our .NET 7 (moving to 8) projects. We use a resx file on the front end to place our values to translate. We can translate them ourselves except that there seems to be no .NET library to access the resx files. We looked at RexXResourceReader but it seems to require the .NET Framework and that .NET only supports .resource binary files. We would like our devs to be able to actually look at the resx files to see the values after translation, not a binary file.

Any ideas?

Thanks!

Apollo9999 commented 10 months ago

To read RESX files from a project in .NET 7/8 at design time, you can use the following steps:

Add a reference to the System.Resources.ResourceManager namespace. Create a new instance of the ResourceManager class, passing in the name of the RESX file and the assembly containing the RESX file. Call the GetString() method on the ResourceManager object to retrieve the value of a resource string. For example, the following code shows how to read the value of the Greeting resource string from the MyResources.resx file:

using System.Resources;

namespace MyApp { public class MyClass { public static string GetGreeting() { ResourceManager manager = new ResourceManager("MyApp.MyResources", Assembly.GetExecutingAssembly()); return manager.GetString("Greeting"); } } } You can also use the ResourceManager class to read other types of resources, such as images, icons, and audio files.

To use the ResourceManager class at design time, you can add it to a code file that is used to generate a designer file. For example, you could add the following code to the MyClass.cs file:

using System.Resources;

namespace MyApp { public class MyClass { private static ResourceManager manager = new ResourceManager("MyApp.MyResources", Assembly.GetExecutingAssembly());

    public static string GetGreeting()
    {
        return manager.GetString("Greeting");
    }
}

}

Then, you could add the MyClass class to a form or other control. The designer file will generate code that will initialize the ResourceManager object and read the resources from the RESX file at design time.

Note that the ResourceManager class is also available in .NET 6 and earlier versions of .NET.