2014-01-29 63 views
0

我創建了用於獲取資源值的簡單控制檯應用程序。應用程序正在爲現有資源密鑰工作。但是對於不存在的resourceKeys引發MissingManifestResourceException。我的代碼有什麼問題嗎?資源文件的構建操作被設置爲嵌入式資源。當在資源文件中找不到資源鍵時拋出MissingManifestResourceException

的Program.cs

using Framework; 

namespace ResourcesConsole 
{ 
    class Program 
    { 
    static void Main(string[] args) 
    { 
     string resourceValue = CustomResourceManager.GetResourceValue("notExistingResourceKey"); 
    } 
    } 
} 

CustomResourceManager.cs

using System.Collections.Generic; 
using System.Globalization; 
using System.Reflection; 
using System.Resources; 

namespace Framework 
{ 
    public class CustomResourceManager 
    { 
    private static Dictionary<string, ResourceManager> _resourceManagerDict; 

    static CustomResourceManager() 
    { 
     _resourceManagerDict = new Dictionary<string, ResourceManager>(); 

     string defaultResourceManagerName = "Framework.CustomResources"; 
     ResourceManager defaultResourceManager = new System.Resources.ResourceManager(defaultResourceManagerName, Assembly.GetExecutingAssembly()); 

     _resourceManagerDict.Add(defaultResourceManagerName, defaultResourceManager); 
    } 

    public static string GetResourceValue(string key, string language = "en") 
    { 
     CultureInfo culture = new CultureInfo(language); 

     string value = null; 

     foreach (var resourceManager in _resourceManagerDict) 
     { 
     value = resourceManager.Value.GetString(key, culture); // MissingManifestResourceException is thrown when resource key is not found in resource file (should return null) 

     if (value != null) 
      return value; 
     } 

     return key; 
    } 
    } 
} 

Solution

+0

神祕的問題。當您使用不存在的資源時,您還期望發生什麼? –

+0

GetString方法應根據文檔返回空值http://msdn.microsoft.com/cs-cz/library/bsb0cfet(v=vs.110).aspx – Czechtim

+0

這不是異常告訴你的。無法找到整個資源塊。您將錯誤的參數傳遞給ResourceManager構造函數。通過運行ildasm.exe並查看清單中的.mresource指令來仔細檢查流名稱。 –

回答

1

我找到了解決辦法。問題在於我缺少用於不變(或默認)文化的資源文件。因此,我將CustomeResources.en.resx更名爲CustomeResources.resx,並且它工作正常