Search code examples
c#.netasp.net-mvc-4localizationresx

Access resource string for specific (non-current) culture


I have an ASP.NET MVC4 application with two resource files in a "Resources" folder, like so:

Project
 Resources
  Resources.fr-CA.resx
  Resources.resx

I set the current culture based on a user setting and everything works fine with this setup.

However, I have a class that handles errors, both displaying them to the user and logging them in the database. What I'd like is to display the error message using the user's current culture, but log it in the database using the English messages.

I did some research and found a couple options to get a resource string for a specific culture, but I'm having problems with them.

HttpContext.GetLocalResourceString("~/Resources/Resources.resx", "Error_Message", CultureInfo.CreateSpecificCulture("en-US")) throws The resource class for this page was not found. Please check if the resource file exists and try again. I've tried messing with the uri to no avail.

HttpContext.GetGlobalResourceString("Resources", "Error_Message", CultureInfo.CreateSpecificCulture("en-US")) always returns null.

How can I accomplish this (getting a resource string for a specific culture without changing Thread.CurrentThread.CurrentCulture)?


Solution

  • Do not use resource strings for logging.

    • Resource string may be changed without relation to the code and thus make logs less searchable.
    • It is harder to understand what will be written to a log file if string is not inline in the code.

    But if you really need to get string from other language use lower level API to grab correct resource set and get string: ResourceManager.GetResourceSet and ResourceSet.GetString