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();

 

輸出結果:

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM