c# 配置文件之configSections配置(三)

使用IConfigurationSectionHandler配置configSections

·步骤1:定义一个实体类

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 using System.Threading.Tasks;
 6 
 7 namespace ConsoleApplication1
 8 {
 9     /// <summary>
10     /// 说明:
11     /// 创建日期:2016/10/27 8:54:11
12     /// 创建人:曹永承
13     /// </summary>
14     public class Conn
15     {
16         public string DataBase { get; set; }
17 
18         public string Server { get; set; }
19 
20         public string UserId { get; set; }
21 
22         public string Password { get; set; }
23 
24         public override string ToString()
25         {
26             return string.Format("server={0};database={1};user id={2};password={3}", Server, DataBase, UserId, Password);
27         }
28     }
29 }

步骤2:定义一个ConnSectionHandler类实现IConfigurationSectionHandler接口

 1 using System.Configuration;
 2 using System.Xml;
 3 
 4 namespace ConsoleApplication1.config
 5 {
 6     /// <summary>
 7     /// 说明:
 8     /// 创建日期:2016/10/27 8:52:35
 9     /// 创建人:曹永承
10     /// </summary>
11     public class ConnSectionHandler : IConfigurationSectionHandler
12     {
13         public object Create(object parent, object configContext, XmlNode section)
14         {
15             Conn conn = new Conn();
16 
17             if (section != null)
18             {
19                 foreach (XmlNode node in section.ChildNodes)
20                 {
21                     switch (node.Name)
22                     {
23                         case "server":
24                             conn.Server = node.SelectSingleNode("@value").InnerText;
25                             break;
26                         case "database":
27                             conn.DataBase = node.SelectSingleNode("@value").InnerText;
28                             break;
29                         case "userid":
30                             conn.UserId = node.SelectSingleNode("@value").InnerText;
31                             break;
32                         case "password":
33                             conn.Password = node.SelectSingleNode("@value").InnerText;
34                             break;
35                     }
36                     
37                 }
38             }
39 
40             return conn;
41         }
42     }
43 }

步骤3:配置xml

1 <configSections>
2   <section name="conn" type="ConsoleApplication1.config.ConnSectionHandler,ConsoleApplication1"/>
3 </configSections>
4 <conn>
5   <server value="(local)"/>
6   <database value="testDB"/>
7   <userid value="sa"/>
8   <password value="123456"/>
9 </conn>

步骤4:测试代码

1 Conn conn = ConfigurationManager.GetSection("conn") as Conn ;
2 Console.WriteLine(conn); 
3 Console.ReadKey();

输出结果:

原文地址:https://www.cnblogs.com/caoyc/p/6002702.html