如何重新获取从组件配置文件的AppSettings? [英] How do I retrieve AppSettings from the assembly config file?

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

问题描述

我想检索调用组件配置文件中AppSetting键:MyAssembly.dll.config。下面是配置文件的一个示例:

 <结构>
    <的appSettings>
        <添加键=的myKey值=MYVAL/>
    < /的appSettings>
< /结构>
 

这里的code检索它:

  VAR的myKey = ConfigurationManager.AppSettings [的myKey];
 

解决方案

使用 OpenMappedExeConfiguration 给你回一个配置对象,你可以用它来窥视到的类库的配置(并存在有将在主应用程序的配置覆盖那些由同一个名字的设置):

  ExeConfigurationFileMap地图=新ExeConfigurationFileMap();
map.ExeConfigFilename =ConfigLibrary.config;

配置libConfig = ConfigurationManager.OpenMappedExeConfiguration(地图,ConfigurationUserLevel.None);

AppSettingsSection部=(libConfig.GetSection(的appSettings)作为AppSettingsSection);
值= section.Settings [测试]值。
 

但那些是唯一的主要的应用程序的配置,也不要在类库自己的配置存在设置还是通过 ConfigurationManager中静态类访问:

串序列= ConfigurationManager.AppSettings [串行];

这仍然有效 - 类库的配置只隐藏那些内部的配置文件的设置;再加上你需要使用 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天全站免登陆