Search code examples
c#.netasp.net-mvcsystemresourcemanager

How to use ResourceManager and resources file in ASP.NET?


I have the following method:

    private void SetResources(string filename = ResxFileName)
    {
        if (_resourceManager == null)
        {
            _resourceManager = new ResourceManager(filename + ".Strings", GetType().Assembly);
        }
    }

If ResxFileName = "Example", where would Example.Strings.resx need to be located in the project in order for it to be accessed? I've tried placing it in the Properties of the project under the Solution Explorer, but whenever GetString("ExampleString") is called and ExampleString exists as a Name and has a value in Example.Strings.resx, I get the following System.Exception:

Could not find any resources appropriate for the specified culture or the neutral culture. Make sure \"Example.Strings.resources\" was correctly embedded or linked into assembly \"ProjectName\" at compile time, or that all the satellite assemblies required are loadable and fully signed.

I've tried running Custom Tool and ensured that the Build Action is set to "Embedded Resource", as others who have posted similar issues have mentioned. These solutions have not resolved the exception.


Solution

  • It looks like you need to flip the filename, Strings would be the filename.

    As to where to place the files, it depends , for a web project it should be in App_GlobalResources

    Try this

    private void SetResources(string filename = ResxFileName)
    {
        if (_resourceManager == null)
        {
            Assembly assembly = System.Reflection.Assembly.Load("App_GlobalResources");
            _resourceManager = new ResourceManager("Resources." + filename, assembly);
        }
    }
    

    For example you would put Strings.en-US, Strings.fr resource files in the App_GlobalResources folder.

    EDIT:

    I don't know what to add, this is the correct way of doing, for the sake of time, I created a demo project for you.

    DEMO DOWNLOAD

    Look inside of the HomeController to see the example.