Patrick Desjardins Blog
Patrick Desjardins picture from a conference

Getting resource value with explicit localization

Posted on: 2012-06-19

Sometime, it's interesting to get a string value from a resource file without getting the one from the current Thread.CurrentThread.CurrentUICulture. Some scenario may be that you are logged in a specific language and you need to sent something to someone who is in a different language.

To be able to do this, you need to change the line of code that use the static property and to call the ResourceManager instead.

Let say that your resource file name is "MyResource.resx". If you have set the visibility to public, the file MyResource.Designer.resx will contains a static property for all your entries. If you have a key value of "Res1" inside your file you will have a static property called "Res1" which will return a string.

public class MyResource{ 
  public static string Res1 { 
    get { 
    return ResourceManager.GetString("Res1", resourceCulture); 
    } 
  } 
} 

If you want to have access to a specific language without using the current resource culture, you need to instead calling the resource by this static property to call the resource manager directly.

 //Instead of : 
 string myString = MyResource.Res1; 
 
 //You have to call : 
 string myString = MyResource.ResourceManager.GetString("Res1", new CultureInfo("FR")); 

That's it. Of course, you have to make sure that you have the culture requested otherwise, an exception will be thrown.