在C#中循环使用不同语言/文化的嵌入式资源

前端之家收集整理的这篇文章主要介绍了在C#中循环使用不同语言/文化的嵌入式资源前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
this question开始一级,可以存储所有(并循环)可用资源和相关文化的方式,以允许用户选择特定文化?

进一步说明:

假设有三个资源文件

> GUILanguage.resx
> GUILanguage.fr.resx
> GUILanguage.it.resx

我可以在每个名为LanguageName的字符串中有一个字符串.我如何能够以编程方式循环遍历不同的LanguageName值以列出它们(例如列表框)?

编辑:WinForms项目,嵌入式资源.

解决方法

这是我认为适用于Winforms的解决方案:
// get cultures for a specific resource info
public static IEnumerable<CultureInfo> EnumSatelliteLanguages(string baseName)
{
    if (baseName == null)
        throw new ArgumentNullException("baseName");

    ResourceManager manager = new ResourceManager(baseName,Assembly.GetExecutingAssembly());
    ResourceSet set = manager.GetResourceSet(CultureInfo.InvariantCulture,true,false);
    if (set != null)
        yield return CultureInfo.InvariantCulture;

    foreach (CultureInfo culture in EnumSatelliteLanguages())
    {
        set = manager.GetResourceSet(culture,false);
        if (set != null)
            yield return culture;
    }
}

// determine what assemblies are available
public static IEnumerable<CultureInfo> EnumSatelliteLanguages()
{
    foreach (string directory in Directory.GetDirectories(AppDomain.CurrentDomain.BaseDirectory))
    {
        string name = Path.GetFileNameWithoutExtension(directory); // resource dir don't have an extension...

        // format is XX or XX-something,we discard directories that can't match.
        // could/should be replaced by a regex but we still need to catch cultures errors...
        if (name.Length < 2)
            continue;

        if (name.Length > 2 && name[2] != '-')
            continue;

        CultureInfo culture = null;
        try
        {
            culture = CultureInfo.GetCultureInfo(name);
        }
        catch
        {
            // not a good directory...
            continue;
        }

        string resName = Path.GetFileNameWithoutExtension(Assembly.GetExecutingAssembly().Location) + ".resources.dll";
        if (File.Exists(Path.Combine(Path.Combine(AppDomain.CurrentDomain.BaseDirectory,name),resName)))
            yield return culture;
    }
}

以下是如何将它用于WindowsFormsApplication1:

List<CultureInfo> cultures = new List<CultureInfo>(EnumSatelliteLanguages("WindowsFormsApplication1.GUILanguage"));

猜你在找的C#相关文章