.NET读取指定Config配置文件和自定义节点

.NET程序默认带的配置文件是app.config和web.config,我们也可以读取指定文件,通过下面代码,

public static Configuration GetConfig(string filename) {
ExeConfigurationFileMap map = new ExeConfigurationFileMap();
map.ExeConfigFilename = System.AppDomain.CurrentDomain.BaseDirectory + @"\Configs\" + filename;
Configuration config = ConfigurationManager.OpenMappedExeConfiguration(map, ConfigurationUserLevel.None);
return config;
}

我们在config文件里定义一个自定义简单集合节点,自定义节点通过configSections实现,

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>
    <section name="Children" type="System.Configuration.DictionarySectionHandler"/>
  </configSections>
  <Children>
    <add key="老大" value="1" />
    <add key="老二" value="2" />
    <add key="老三" value="3" />
  </Children>
</configuration>

 

public static object GetConfigurationValues(Configuration config, string sectionName) {
    ConfigurationSection section = config.GetSection(sectionName);
    string xml = section.SectionInformation.GetRawXml();
    XmlDocument doc = new XmlDocument();
    doc.Load(XmlReader.Create(new StringReader(xml)));
    string type = section.SectionInformation.Type;
    string assemblyName = typeof(IConfigurationSectionHandler).Assembly.GetName().FullName;
    ObjectHandle configSectionHandlerHandle = Activator.CreateInstance(assemblyName, section.SectionInformation.Type);
    if (configSectionHandlerHandle != null) {
    IConfigurationSectionHandler handler = configSectionHandlerHandle.Unwrap() as IConfigurationSectionHandler;
    return handler.Create(null, null, doc.DocumentElement);
    }
    return null;
}

 调用,

Configuration config = GetConfig("test.config");
Hashtable ht = (Hashtable)GetConfigurationValues(config, "Children");

源码下载

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

stdl

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值