如何在WPF中使用外部配置文件?

问题描述:

我想设置一个外部配置文件,我可以将其存储在我的WPF应用程序的目录中,而不必在创建我的程序时使用我的exe文件的目录。如何在WPF中使用外部配置文件?

我创建了一个App.Config文件,并将System.Configuration添加到我的程序集中。我App.Config中有:

<?xml version="1.0" encoding="utf-8" ?> 
<configuration> 
    <appSettings file="sd.config"> 
    <add key="username" value="joesmith" /> 
    </appSettings> 
</configuration> 

和我sd.config(外部文件),这是在我的项目的根就目前而言,我用

我的主窗口CS类有

<?xml version="1.0"?> 
<appSettings> 
    <add key="username1" value="janedoe" /> 
</appSettings> 

string username = ConfigurationManager.AppSettings.Get("username1"); 

它返回一个空字符串。当我只是从App.Config检索用户名字段,它的作品。我错过了什么?非常感谢!

参见ConfigurationManager文档:

AppSettings属性:

获取AppSettingsSection数据为当前应用程序的默认 配置。

你需要做一些额外的工作来获取数据不是在应用程序的默认配置文件。

除了使用file=属性,添加一个关键看你<appSettings>定义辅助配置文件的位置,就像这样:

<add key="configFile" value="sd.config"/> 

然后,为了使用ConfigurationManager中从二级拉设置配置文件,你需要使用它的OpenMappedExeConfiguration method,这应该看起来有点像这样:

var map = new ExeConfigurationFileMap(); 
map.ExeConfigFilename = Path.Combine(
     AppDomain.CurrentDomain.SetupInformation.ApplicationBase, 
     ConfigurationManager.AppSettings["configFile"] 
); 

//Once you have a Configuration reference to the secondary config file, 
//you can access its appSettings collection: 
var config = ConfigurationManager.OpenMappedExeConfiguration(map, ConfigurationUserLevel.None); 

var userName1 = config.AppSettings["username1"]; 

这些代码可能不会死在你的例子,但我希望它可以让你在th正确的轨道!

+0

非常感谢! – Drew 2010-12-23 13:02:50