如何从程序集配置文件中检索 AppSettings? [英] How do I retrieve AppSettings from the assembly config file?

查看:24
本文介绍了如何从程序集配置文件中检索 AppSettings?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从名为 MyAssembly.dll.config 的程序集配置文件中检索 AppSetting 密钥.这是配置文件的示例:

<预><代码><配置><应用设置><add key="MyKey" value="MyVal"/></appSettings></配置>

这是检索它的代码:

var myKey = ConfigurationManager.AppSettings["MyKey"];

解决方案

使用 OpenMappedExeConfiguration 为您提供一个配置"对象,您可以使用该对象查看类库的配置(以及设置存在的将覆盖主应用程序配置中同名的那些):

ExeConfigurationFileMap map = new ExeConfigurationFileMap();map.ExeConfigFilename = "ConfigLibrary.config";配置 libConfig = ConfigurationManager.OpenMappedExeConfiguration(map, ConfigurationUserLevel.None);AppSettingsSection 部分 = (libConfig.GetSection("appSettings") as AppSettingsSection);value = section.Settings["Test"].Value;

但是那些对于主应用程序的配置来说是唯一的并且在类库自己的配置中不存在的设置仍然可以通过 ConfigurationManager 静态类访问:

string serial = ConfigurationManager.AppSettings["Serial"];

那仍然有效 - 类库的配置只隐藏其配置文件中的那些设置;此外,您还需要使用libConfig 实例来访问类库自己的配置设置.

这两个世界(主 app.config、classlibrary.config)可以完全且非常愉快地共存 - 根本没有问题!

马克

I would like to retrieve the AppSetting key from the assembly config file called: MyAssembly.dll.config. Here's a sample of the config file:

<configuration>
    <appSettings>
        <add key="MyKey" value="MyVal"/>
    </appSettings>
</configuration>

Here's the code to retrieve it:

var myKey = ConfigurationManager.AppSettings["MyKey"];

解决方案

Using the OpenMappedExeConfiguration gives you back a "Configuration" object which you can use to peek into the class library's config (and the settings that exist there will override the ones by the same name in the main app's config):

ExeConfigurationFileMap map = new ExeConfigurationFileMap();
map.ExeConfigFilename = "ConfigLibrary.config";

Configuration libConfig = ConfigurationManager.OpenMappedExeConfiguration(map, ConfigurationUserLevel.None);

AppSettingsSection section = (libConfig.GetSection("appSettings") as AppSettingsSection);
value = section.Settings["Test"].Value;

But those settings that are unique to the main app's config and do not exist in the class library's own config are still accessible via the ConfigurationManager static class:

string serial = ConfigurationManager.AppSettings["Serial"];

That still works - the class library's config only hides those settings that are inside its config file; plus you need to use the "libConfig instance to get access to the class library's own config settings, too .

The two worlds (main app.config, classlibrary.config) can totally and very happily co-exist - not a problem there at all!

Marc

这篇关于如何从程序集配置文件中检索 AppSettings?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆