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

前端 未结 7 537
青春惊慌失措
青春惊慌失措 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:41

    A generic answer where the resource type to search is specified. Uses reflection but is cached.

    Usage:

    List comboBoxEntries = CommonUtil.CulturesOfResource()
        .Select(cultureInfo => cultureInfo.NativeName)
        .ToList();
    

    Implementation (Utility Class):

    static ConcurrentDictionary> __resourceCultures = new ConcurrentDictionary>();
    
    /// 
    /// Return the list of cultures that is supported by a Resource Assembly (usually collection of resx files).
    /// 
    static public List CulturesOfResource()
    {
        return __resourceCultures.GetOrAdd(typeof(T), (t) =>
        {
            ResourceManager manager = new ResourceManager(t);
            return CultureInfo.GetCultures(CultureTypes.AllCultures)
                .Where(c => !c.Equals(CultureInfo.InvariantCulture) && 
                            manager.GetResourceSet(c, true, false) != null)
                .ToList();
        });
    }
    

    It may suffer the same issue with the accepted answer in that all the language resources will probably be loaded.

提交回复
热议问题