Home > database >  Why is setting globalization culture not causing my localized string to be used?
Why is setting globalization culture not causing my localized string to be used?

Time:11-17

In a .Net 6 console app, I have set up a String resource Strings in a separate library project such that String.MyString = "string" in Strings.resx and "foreign string" in Strings.sv.resx... this was done by simply adding a new Resources File to the project and using the visual tool to add strings.

I want to set my application culture to locale "sv" throughout so I wrote this test code:

internal class Program
{
  private static async Task Main(string[] args)
  {
    var culture = CultureInfo.CreateSpecificCulture("sv");
    Console.WriteLine($"1: {Strings.MyString}");
    CultureInfo.DefaultThreadCurrentCulture = culture;
    Console.WriteLine($"2: {Strings.MyString}");
    Thread.CurrentThread.CurrentCulture = culture;
    Console.WriteLine($"3: {Strings.MyString}");
    Strings.Culture = culture;
    Console.WriteLine($"4: {Strings.MyString}");
    ...

Output:

1: string
2: string
3: string
4: foreign string

My expectation is that only the first line would be "string" since I change the culture. Forcibly changing the localization on Strings is the only way that works and seems a really bad way to do it.

Every example I have seen seems to favor the Thread approach (3) so what is not working? Isn't Strings supposed to use the thread/application locale?

CodePudding user response:

Not sure about exact difference between CurrentUICulture and CurrentCulture of Thread.CurrentThread but changing CurrentUICulture is enough for changes to be applied.

I have two files in project:

  1. Strings.resx - default culture strings are located here (English)

  2. Strings.ru.resx - Russian-translated strings are here

    Console.WriteLine($"Default culture: {Strings.TestString}");
    
    var ruCulture = new CultureInfo("ru");
    
    Thread.CurrentThread.CurrentUICulture = ruCulture;
    
    Console.WriteLine($"{ruCulture}: {Strings.TestString}");
    

Output:

Default culture: English
ru: Русский

As a side note, no matter what your default actual culture is - it will search resources in primary *.resx file (without culture suffix).
But when changing to alternative culture .resx with suffix will be searched (.ru.resx in my case).

PS: Rider has nice designer to edit several files from single form. Not sure about Visual Studio.

  • Related