C# 自定义Section

一、在App.config中自定义Section,这个使用了SectionGroup

<?xml version="1.0" encoding="utf-8" ?>
<configuration>

<configSections> <sectionGroup name="IpTables"> <section name="IPs" type="Section.Test.MySectionHandler,Section.Test"/> </sectionGroup> </configSections> <IpTables> <IPs> <add key="ip" value="127.0.0.1"/> <add key="port" value="8888"/> </IPs> </IpTables> </configuration>

xml中的section 需要显示配置自定义的处理程序,即type属性
二、创建处理程序 MySectionHandler

 1  //实现 IConfigurationSectionHandler接口,并且读取自定义Section
 2     public class MySectionHandler : IConfigurationSectionHandler
 3     {
 4           public object Create(object parent, object configContext, XmlNode section)
 5            {
 6               var dic= new Dictionary<string, string>();
 7                 //可能会出现注释,所以需要显示过滤xml元素
 8                foreach (XmlElement childNode in section.ChildNodes.OfType<XmlElement>())
 9                {
10              
11                  dic.Add(childNode.Attributes["key"].InnerText,childNode.Attributes["value"].InnerText);
12                   
13                }
14             return dic;
15            }
16     }

 

执行处理程序代码如下:

var dic= ConfigurationManager.GetSection("IpTables/IPs") as IDictionary<string,string>;

注意事项:

1.获取自定义Section,如果是SectionGroup,则需要 SectionGroup/Section 这种格式获取

2.一般该代码写在应用程序初始化处,只加载一次,然后将其值缓存至内存中即可使用

3.<configSections> 元素必须是 configuration 元素的第一个子元素

 三、如何自定义比如log4net.config中那样的节点?

       没难度,其实就是基本的xml操作了。

转载于:https://www.cnblogs.com/gaobing/p/6047746.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值