2017-06-24 45 views
0

我有一個動態數量的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(); 
     } 

但它會採取一切來自單個資源的翻譯,但由於我擁有大量的資源文件,因此它不太適合我。

在此先感謝!

回答

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; 
} 

請記住,這不是最快的方法,因爲它使用了反射。所以考慮使用緩存策略。

0

這爲我工作:

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的另一個名字)作爲關鍵。

+0

它不會工作,因爲我有70多個單獨的資源文件...例如 - Exceptions.resx,MyCool.resx,SomethingElse.resx – Maris

+0

噢,好的:)這讓事情變得有趣。所以你想要輸出包含所有資源文件中的所有字符串,按文化分組?或者只是來自當前文化的所有資源的字符串? –

+0

正是。我已經發明瞭自己的自行車,至少看看它有效。 :) – Maris

相關問題