.NET配置系统 - 剖析AppSettings实现
1. 浏览AppSettings
AppSettings为程序员提供了方便简洁的配置存储,下面是一个典型的AppSettings在应用程序的配置文件:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<clear/>
<add key="key1" value="value1"/>
<add key="key2" value="value2 A"/>
<add key="key2" value="value2 B"/>
</appSettings>
</configuration>
<configuration>是.NET配置系统的XML根节点,接着<appSettings>中<clear/>上删除继承下来的映射AppSettings值(如果有的话),通过<add>来添加一对键值,如果两个键相同,如例子中的两个key2,那么之前的键值会被后来的改写,即这个配置文件AppSettings中key2键的值是value2 B.
AppSettings是一个ConfigurationSection,那么我们首先可以通过Configuation的GetSection可以浏览其内容,当然Configuration类提供一个AppSettings属性来方便用户,看其源代码,其实就是用GetSection来返回”appSettings”ConfigurationSection;
//Configuration类的AppSettings属性源代码
public AppSettingsSection AppSettings
{
get
{
return (AppSettingsSection)this.GetSection("appSettings");
}
}
那么通过Configuration类浏览AppSettings就是这样的:
(代码1:通过Configuration.GetSection浏览)
Configuration conf =
ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
AppSettingsSection appSet = conf.AppSettings;
foreach (KeyValueConfigurationElement ele in appSet.Settings)
Console.WriteLine("键:{0} 值:{1}", ele.Key, ele.Value);
看到这里,有些读者可能发现这个并不是最常用的浏览方法,是的,上述方法是浏览.NET配置文件的最原始方法,优点是灵活可读可写,缺点是有些复杂,对于AppSettings这种方便简洁的配置存储,我们还可以使用另一种更常见的方法,就是用ConfigurationManager类。这个类的AppSettings属性返回一个NameValueCollection(此类在System.Collections.Specialized命名空间内)可以直接供用户查询。
(代码2:通过ConfigurationManager浏览)
System.Collections.Specialized.NameValueCollection nvc =
ConfigurationManager.AppSettings;
foreach (string key in nvc.AllKeys)
Console.WriteLine("键:{0} 值:{1}", key, nvc[key]);
两种方法输出都一样:
键:key1 值:value1
键:key2 值:value2 B
2. 寻找AppSettings根源
我们说AppSettings本质上是一个ConfigurationSection,接下来是时候探索一下这个ConfigurationSection了,先来看看列举一下本地应用程序配置文件继承下来的所有ConfigurationSection。
这里主要通过Configuration类的Sections和SectionGroups属性来枚举
Configuration conf = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
Console.WriteLine("本地配置文件: {0}\n", conf.FilePath);
Console.WriteLine("=== 所有SectionGroup");
foreach (ConfigurationSectionGroup grp in conf.SectionGroups)
Console.WriteLine(grp.SectionGroupName);
Console.WriteLine();
Console.WriteLine("=== 所有Section");
foreach (ConfigurationSection sec in conf.Sections)
Console.WriteLine(sec.SectionInformation.SectionName);
输出结果:
本地配置文件: E:\My Documents\Visual Studio 2008\Projects\TTC\TTC\bin\Release\Mg
en.exe.Config
=== 所有SectionGroup
system.serviceModel
system.net
system.transactions
system.web
system.runtime.serialization
system.serviceModel.activation
system.xml.serialization
=== 所有Section
system.data
windows
system.webServer
mscorlib
system.data.oledb
system.data.oracleclient
system.data.sqlclient
configProtectedData
satelliteassemblies
system.data.dataset
startup
system.data.odbc
system.diagnostics
runtime
system.codedom
system.runtime.remoting
connectionStrings
assemblyBinding
appSettings
system.windows.forms
AppSettings必须在其中(黄色标注)
补充:Web开发 , ASP.Net ,