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

Dre*_*rew 0 wpf configuration external

我想设置一个外部配置文件,我可以将它存储在我的 WPF 应用程序的目录中,也不一定是我创建程序时的 exe 目录。

我创建了一个 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>
Run Code Online (Sandbox Code Playgroud)

我的 sd.config(外部文件)现在在我的项目的根目录中,有

<?xml version="1.0"?>
 <appSettings>
   <add key="username1" value="janedoe" />
</appSettings>
Run Code Online (Sandbox Code Playgroud)

在我使用的 MainWindow cs 类中

string username = ConfigurationManager.AppSettings.Get("username1");
Run Code Online (Sandbox Code Playgroud)

它返回一个空字符串。当我刚刚从 App.Config 检索用户名字段时,它可以工作。我错过了什么?非常感谢!

Dan*_*n J 5

请参阅ConfigurationManager上的文档:

AppSettings 属性:

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

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

不要使用该file=属性,而是向您添加一个键来<appSettings>定义辅助配置文件的位置,如下所示:

<add key="configFile" value="sd.config"/>
Run Code Online (Sandbox Code Playgroud)

然后,为了使用 ConfigurationManager 从辅助配置文件中提取设置,您需要使用其OpenMappedExeConfiguration 方法,它应该看起来像这样:

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"];
Run Code Online (Sandbox Code Playgroud)

对于您的示例,该代码可能不会完全正确,但希望它能让您走上正轨!