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


在很多時候我們需要自定義我們自己的自定義App.config 文件,而微軟為我們提供了默認的

System.Configuration.DictionarySectionHandler

System.Configuration.NameValueSectionHandler      

System.Configuration.SingleTagSectionHandler

 

DictionarySectionHandler使用

  DictionarySectionHandler的工作方式與NameValueFileSectionHandler幾乎相同,其區別是DictionarySectionHandler返回HashTable對象,而后者返回的是NameValueCollection。

1 <configSections>
2   <section name="mailServer" type="System.Configuration.DictionarySectionHandler,System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"/>
3 </configSections>
4 <mailServer>
5   <add key="url" value="mail.163.com"/>
6   <add key="username" value="admin"/>
7   <add key="password" value="123456"/>
8 </mailServer>

  使用代碼

1 IDictionary dic = ConfigurationManager.GetSection("mailServer") as IDictionary; 
2 Console.WriteLine(dic);
3 foreach (var key in dic.Keys)
4 {
5     Console.WriteLine("{0}:{1}", key, dic[key]);
6 }
7 Console.ReadKey();

 

由於DictionarySectionHandler返回的是HashTable對象,而HashTable中的Key是唯一的。那么DictionarySectionHandler如果配置了相同的Key,后面的值會覆蓋前面的值。

還是上面的的例子,我們將配置文件修改一下

1 <mailServer>
2   <add key="url" value="mail.163.com"/>
3   <add key="username" value="admin"/>
4   <add key="password" value="123456"/>
5   <add key="password" value="12345678"/>
6 </mailServer>

接下來看看輸出結果:

 

 

NameValueSectionHandler使用

  xml配置

1 <configSections>
2   <section name="mailServer" type="System.Configuration.NameValueSectionHandler,System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"/>
3 </configSections>
4 <mailServer>
5   <add key="url" value="mail.163.com"/>
6   <add key="username" value="admin"/>
7   <add key="password" value="123456"/>
8   <add key="password" value="12345678"/>
9 </mailServer>

  代碼:

1 NameValueCollection mailServer = ConfigurationManager.GetSection("mailServer") as NameValueCollection;
2 Console.WriteLine(mailServer);
3 foreach (var key in mailServer.AllKeys)
4 {
5     Console.WriteLine("{0}:{1}",key,mailServer[key]);
6 }
7 Console.ReadKey();

  輸出結果:

 

 

SingleTagSectionHandler使用

  SingleTagSectionHandler和DictionarySectionHandler一樣,同樣返回的是Hashtable對象,只是書寫結構不一樣。

  xml配置:

1 <configSections>
2   <section name="mailServer" type="System.Configuration.SingleTagSectionHandler,System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"/>
3 </configSections>
4 <mailServer url="mail.163.com" username="admin" password="12345678"/>

  代碼:

1 IDictionary mailServer = ConfigurationManager.GetSection("mailServer") as Hashtable ;
2 Console.WriteLine(mailServer);
3 foreach (var key in mailServer.Keys)
4 {
5     Console.WriteLine("{0}:{1}", key, mailServer[key]);
6 }    
7  Console.ReadKey();

  輸出結果:

 


免責聲明!

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



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