frenchie
frenchie

Reputation: 51937

Localization with resource file not working when setting culture at runtime

I'm setting the page culture at runtime in the code-behind like this:

System.Threading.Thread.CurrentThread.CurrentCulture = new CultureInfo("fr-FR");
System.Threading.Thread.CurrentThread.CurrentUICulture = new CultureInfo("fr-FR");
Page.Culture = "fr-FR";

The resource files are in the GlobalResource folder and I've got 2 files: SomeFile.resx and SomeFile.fr.resx

In the markup page, I have a literal that looks like this:

<asp:Literal runat="server" ID="test" Text="<%$ Resources:SomeFile, SomeKey%>" />

If the code that sets the culture is commented out then the literal will take the value that's in the SomeFile.resx but if I run the code that sets the culture then I also get the value that's in the SomeFile.resx file instead of the value that's in the SomeFile.fr.resx file. I also tried with the culture info set to just "fr" to see if that makes any difference but it doesn't.

What do I need to change?

Upvotes: 1

Views: 4731

Answers (2)

frenchie
frenchie

Reputation: 51937

Ok, for those who come here, I've figured it out.

1) Put the resource files in the App_GlobalResources folder. For example, you might have SomeFile.resx and SomeFile.fr.resx

2) In your code behind, set the culture like this:

System.Threading.Thread.CurrentThread.CurrentCulture = new CultureInfo("fr-FR");
System.Threading.Thread.CurrentThread.CurrentUICulture = new CultureInfo("fr-FR");
Page.Culture = "fr-FR";

3) Then, to access the values, you write this:

string SomeValue = GetGlobalResourceObject("SomeFile", "SomeKey").ToString();

I think is is the simplest way to do it.

Upvotes: 0

Kjata30
Kjata30

Reputation: 751

The Microsoft article for locating localized resources provides a good example of how to do this. From what you've written, it looks like you are not creating a new ResourceManager object to use the culture:

private ResourceManager rm { get; set; }

protected void Page_Load()
{
  var newCulture = new CultureInfo("fr-FR");
  Thread.CurrentThread.CurrentCulture = newCulture;
  Thread.CurrentThread.CurrentUICulture = newCulture;
  Page.Culture = "fr-FR";
  this.rm = new ResourceManager("SomeFile", typeof(Program).Assembly);

  this.test.Text = rm.GetString("SomeKey");
}

Upvotes: 3

Related Questions