2010-12-22 51 views
0

我想設置一個外部配置文件,我可以將其存儲在我的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檢索用戶名字段,它的作品。我錯過了什麼?非常感謝!

回答

4

參見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

相關問題