2013-02-27 113 views
0

下面的代碼不起作用。它不會從TestApp.Config文件獲得應用程序設置。你知道爲什麼嗎?我該如何解決它?如何使用特定的應用程序配置文件

public void GetConfig() 
    { 
    AppDomain.CurrentDomain.SetData("APP_CONFIG_FILE", @"C:\dev\VS\ProofOfConcept\ProofOfConcept\TestApp.config"); 
    var a = ConfigurationManager.AppSettings; 
    } 
+0

試試這個答案 - 它爲我工作:http://stackoverflow.com/a/6151688/67038我結束了適應一下代碼,並寫了一個擴展方法ApplicationSettingsBase – JMarsch 2013-02-27 18:14:16

+0

最明顯的事情我看到你是永遠不會加載文件。無論如何,您只需設置文件的位置,而不是將文件放置在真實的位置。 – 2013-02-27 18:27:37

+0

[在運行時更改默認app.config]的可能重複(http://stackoverflow.com/questions/6150644/change-default-app-config-at-runtime) – 2015-12-30 14:19:42

回答

4

post可能幫助:

在這裏張貼的解決方案有一個方法ResetConfigurationMechanism()調用CurrentDomain.SetData(...);後,你應該調用。

private static void ResetConfigMechanism() 
{ 
    typeof(ConfigurationManager) 
    .GetField("s_initState", BindingFlags.NonPublic | BindingFlags.Static)                     
    .SetValue(null, 0); 

    typeof(ConfigurationManager) 
    .GetField("s_configSystem", BindingFlags.NonPublic | BindingFlags.Static) 
    .SetValue(null, null); 

    typeof(ConfigurationManager) 
    .Assembly.GetTypes() 
    .Where(x => x.FullName == 
     "System.Configuration.ClientConfigPaths") 
    .First() 
    .GetField("s_current", BindingFlags.NonPublic | BindingFlags.Static) 
    .SetValue(null, null); 
} 
相關問題