通过culture获取所有资源文件的所有翻译

时间:2017-06-24 07:49:24

标签: c# .net

我有动态数量的resx个文件。我需要找到一种优雅的方式来获取文化中所有资源文件的所有翻译,格式如下:

Dictionary<string, string> (key->$"{resourceName}.${translationKey}", value -> translation value)

我知道我可以使用下一种方法:

        ResourceSet resourceSet = MyResource.ResourceManager.GetResourceSet(CultureInfo.CurrentUICulture, true, true);
        foreach (DictionaryEntry entry in resourceSet)
        {
            string resourceKey = entry.Key.ToString();
            string resource = entry.Value.ToString();
        }

但它会从单个资源中获取所有翻译,但由于我有大量的资源文件,因此对我来说不太适合。

提前致谢!

2 个答案:

答案 0 :(得分:1)

这对我有用:

var resourceManager = Properties.Resources.ResourceManager;
var resourceSets = new Dictionary<CultureInfo,ResourceSet>();
CultureInfo[] cultures = CultureInfo.GetCultures(CultureTypes.AllCultures);
foreach (var ci in cultures)
{
    var resourceSet = resourceManager.GetResourceSet(ci, true, false);
    if (resourceSet != null)
        resourceSets.Add(ci, resourceSet);
}

我在解决方案Resources.resxResources.de-DE.resx中有两个资源文件。字典将包含可用的cultureinfos作为键,并将相应的ResourceSet个对象作为值。第一个ResourceSet有? CultureInfo.InvariantCulture(仅限en-US的另一个名称)作为密钥。

答案 1 :(得分:0)

所以,我最终采用了下一种方法:

public Dictionary<string, string> GetAllResources(string culture){
        var result = new Dictionary<string, string>();
        // let's point somehow to our assembly which contains all resource files
        var resourceAssembly = Assembly.GetAssembly(typeof(EnumsResource));
        var resourceTypes = resourceAssembly
            .GetTypes()
            .Where(e => e.Name.EndsWith("Resource"));
        // Culture
        var cultureInfo = new CultureInfo(culture);
        foreach (var resourceType in resourceTypes)
        {
            var resourceManager = (ResourceManager)resourceType.GetProperty("ResourceManager").GetValue(null);
            var resourceName = resourceManager.BaseName.Split('.').Last();
            var resourceSet = resourceManager.GetResourceSet(cultureInfo, true, true);
            foreach (DictionaryEntry entry in resourceSet)
            {
                var resourceKey = $"{resourceName}.{entry.Key}".ToLower();
                var resource = entry.Value.ToString();
                if (!result.ContainsKey(resourceKey))
                {
                    result.Add(resourceKey, resource);
                }
            }
        }

        return result;
}

请记住,这不是最快的方法,因为它使用反射。所以考虑使用缓存策略。