如何在 WPF 中使用外部配置文件?
我想设置一个外部配置文件,可以将其存储在我的 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>
我的 sd.config (外部文件)目前位于我的项目的根目录中,
<?xml version="1.0"?>
<appSettings>
<add key="username1" value="janedoe" />
</appSettings>
在我使用的 MainWindow cs 类中
string username = ConfigurationManager.AppSettings.Get("username1");
,它返回一个空字符串。当我刚刚从 App.Config 检索用户名字段时,它就可以工作。我错过了什么?非常感谢!
i would like to set up an external configuration file that I can store in a directory for my WPF app, not necessarily the directory of my exe when I create my program either.
I created an App.Config file and added System.Configuration to my assembly. My App.Config has:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings file="sd.config">
<add key="username" value="joesmith" />
</appSettings>
</configuration>
and my sd.config (external file) which is in the root of my project for now, has
<?xml version="1.0"?>
<appSettings>
<add key="username1" value="janedoe" />
</appSettings>
in my MainWindow cs class I used
string username = ConfigurationManager.AppSettings.Get("username1");
which returns a null string. when i just retrieve the username field from App.Config it works. What did i miss? Thanks so much!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
请参阅 ConfigurationManager 上的文档:
AppSettings 属性:
您需要做一些额外的工作来获取应用程序的默认配置文件中不存在的数据。
不要使用
file=
属性,而是向
添加一个键来定义辅助配置文件的位置,如下所示: ConfigurationManager 要从辅助配置文件中提取设置,您需要使用其 OpenMappedExeConfiguration 方法,它应该看起来有点像这样:
该代码对于您的示例来说可能不是完全正确的,但希望它能让您走上正轨!
See the documentation on ConfigurationManager:
The AppSettings property:
You need to do a little extra work to get data that isn't in your application's default configuration file.
Instead of using the
file=
attribute, add a key to your<appSettings>
that defines the location of the secondary config file, like so:Then, in order to use ConfigurationManager to pull settings from the secondary config file, you need to use its OpenMappedExeConfiguration method, which should look a little something like this:
That code might not be dead-on for your example, but hopefully it gets you on the right track!