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

时间:2023-09-06 23:03:18
c# 配置文件之configSections配置(二)

在很多时候我们需要自定义我们自己的自定义App.config 文件,而微软为我们提供了默认的

System.Configuration.DictionarySectionHandler

System.Configuration.NameValueSectionHandler      

System.Configuration.SingleTagSectionHandler

DictionarySectionHandler使用

  DictionarySectionHandler的工作方式与NameValueFileSectionHandler几乎相同,其区别是DictionarySectionHandler返回HashTable对象,而后者返回的是NameValueCollection。

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

  使用代码

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

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

由于DictionarySectionHandler返回的是HashTable对象,而HashTable中的Key是唯一的。那么DictionarySectionHandler如果配置了相同的Key,后面的值会覆盖前面的值。

还是上面的的例子,我们将配置文件修改一下

 <mailServer>
<add key="url" value="mail.163.com"/>
<add key="username" value="admin"/>
<add key="password" value="123456"/>
<add key="password" value="12345678"/>
</mailServer>

接下来看看输出结果:

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

NameValueSectionHandler使用

  xml配置

 <configSections>
<section name="mailServer" type="System.Configuration.NameValueSectionHandler,System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"/>
</configSections>
<mailServer>
<add key="url" value="mail.163.com"/>
<add key="username" value="admin"/>
<add key="password" value="123456"/>
<add key="password" value="12345678"/>
</mailServer>

  代码:

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

  输出结果:

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

SingleTagSectionHandler使用

  SingleTagSectionHandler和DictionarySectionHandler一样,同样返回的是Hashtable对象,只是书写结构不一样。

  xml配置:

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

  代码:

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

  输出结果:

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