Programmatic way to get all the available languages (in satellite assemblies)

前端 未结 7 519
青春惊慌失措
青春惊慌失措 2020-11-28 08:11

I\'m designing a multilingual application using .resx files.

I have a few files like GlobalStrings.resx, GlobalStrings.es.resx, GlobalStrings.en.resx, etc. When I wa

7条回答
  •  抹茶落季
    2020-11-28 08:52

    based on answer by @hans-holzbart but fixed to not return the InvariantCulture too and wrapped into a reusable method:

    public static IEnumerable GetAvailableCultures()
    {
      List result = new List();
    
      ResourceManager rm = new ResourceManager(typeof(Resources));
    
      CultureInfo[] cultures = CultureInfo.GetCultures(CultureTypes.AllCultures);
      foreach (CultureInfo culture in cultures)
      {
        try
        {
          if (culture.Equals(CultureInfo.InvariantCulture)) continue; //do not use "==", won't work
    
          ResourceSet rs = rm.GetResourceSet(culture, true, false);
          if (rs != null)
            result.Add(culture);
        }
        catch (CultureNotFoundException)
        {
          //NOP
        }
      }
      return result;
    }
    

    using that method, you can get a list of strings to add to some ComboBox with the following:

    public static ObservableCollection GetAvailableLanguages()
    {
      var languages = new ObservableCollection();
      var cultures = GetAvailableCultures();
      foreach (CultureInfo culture in cultures)
        languages.Add(culture.NativeName + " (" + culture.EnglishName + " [" + culture.TwoLetterISOLanguageName + "])");
      return languages;
    }
    

提交回复
热议问题