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