1

Suppose I have 2 resources files; one's called HomeEN.resx and the other one is called HomeFR.resx. I've looked at online tutorials that show how the selection of the resource file is done automatically, based on the user's setting in his browser.

I want to select the resource file at runtime, something like this:

protected void Page_Load(object sender, EventArgs e)
{      
    switch (TheLanguage) {

       case 1:
            // select the English file HomeEN.resx;
            break;

       case 2:
            // select the French file HomeFR.resx;
            break;
    }
}

How do I write these statements?

halfer
  • 19,824
  • 17
  • 99
  • 186
frenchie
  • 51,731
  • 109
  • 304
  • 510

3 Answers3

3

The correct resource files are automatically read by setting the Page's Culture and UICulture properties. See the MSDN samples

You just need to rename your files to match the expected pattern, Home.en.resx and Home.fr.resx respectively.

devio
  • 36,858
  • 7
  • 80
  • 143
  • I don't like these "automatic" sorceries but I guess for this case it'll be OK. Thanks. – frenchie Sep 09 '14 at 18:01
  • +1 as using standard approach lead to code that will be easier to read (less surprises). @frenchie if you want to do it hard way check out http://stackoverflow.com/questions/8825433/using-resourcemanager and link to [MSDN: Retrieve Resource Values Programmatically](http://msdn.microsoft.com/en-us/library/ms227982%28v=vs.90%29.aspx) provided by DJ KRAZE – Alexei Levenkov Sep 09 '14 at 18:02
  • For some reason, I must be doing something wrong. Can you take a look at this follow-up question: http://stackoverflow.com/questions/25751343/using-localization-and-resource-files-for-asp-net-literal-controls – frenchie Sep 09 '14 at 18:33
1
protected void Page_Load(object sender, EventArgs e)
{      
System.Threading.Thread.CurrentThread.CurrentCulture = someCulture;
    System.Threading.Thread.CurrentThread.CurrentUICulture = someCulture;
}

After that, if you follow @devio's solution above as well, the resource files will be selected automatically.

jle
  • 9,316
  • 5
  • 48
  • 67
1

If you want to access both resources, you can use ResourceManager class

 ResourceManager rm = new ResourceManager("Strings", typeof(Example).Assembly);
string strDE = rm.GetString("TheNameOfTheResource",  new CultureInfo("de"));
string strES = rm.GetString("TheNameOfTheResource",  new CultureInfo("es"));
Naresh
  • 374
  • 1
  • 4