2013-02-27 111 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); 
} 
相关问题