在.NET 1.1下,你必须用过实现IConfigurationSectionHandler接口来进行操作。

但在.NET 2.0下,微软提供了一系列可以对配置文件进行操作的方法,而且非常强大,能够让你随便定义自己的配置节点。在开始之前我们先看看我们想写一个怎样的配置节:

使用ConfigurationManager来写自己的配置文件  <configSections>
使用ConfigurationManager来写自己的配置文件    
<section name="MailSettings" type="MyBlog.MailSection, MyBlog" />
使用ConfigurationManager来写自己的配置文件  
</configSections>

这个地方指定了我们想要写一个MailSettings的节,后面的type标识将会使用MyBlog这个assembly理的MyBlog.MailSection类来识别这个section。


使用ConfigurationManager来写自己的配置文件<MailSettings>
使用ConfigurationManager来写自己的配置文件    
<MailPlugins>
使用ConfigurationManager来写自己的配置文件      
<add name="Server" value="" />
使用ConfigurationManager来写自己的配置文件      
<add name="Title" value="" />
使用ConfigurationManager来写自己的配置文件      
<add name="Body" value="" />
使用ConfigurationManager来写自己的配置文件    
</MailPlugins>
使用ConfigurationManager来写自己的配置文件  
</MailSettings>

这个地方有是我们自定义的一些配置了,value就是我们所需要的一些值。

现在目标已经有了,下面就是怎么去用这些API来读出我们需要的值:

首先很自然我们需要MailSettings的这个section,于是我们定义类:

使用ConfigurationManager来写自己的配置文件    public sealed class MailSection : ConfigurationSection
    }

一个ConfigurationSection可以有自己的一些attribute,这些网上资料很多,我就不详解了。我关心的是下面的MailPlugins这层,这层在配置文件上被称为ConfigurationElementCollection,也就是一些ConfigurationElement的集合。那么我们先定义所需要的ConfigurationElement:

使用ConfigurationManager来写自己的配置文件    public sealed class MailPluginElement : ConfigurationElement
    }


 接着是定义这个ConfigurationElement的集合:

使用ConfigurationManager来写自己的配置文件    public sealed class MailPluginElementCollection : ConfigurationElementCollection
    }

默认的抽象类是让我们必须override上面的两个保护方法。但是这样是不能满足我们的要求的,我们希望用add key 和 value这种形式来配置:

使用ConfigurationManager来写自己的配置文件        public override ConfigurationElementCollectionType CollectionType
        }

 这里相当重要!需要使用AddRemoveClearMap来确保配置处理节能够识别<add key="" value="" />,如果配置为别的会报给你add节无法识别的错误!

那么最后我们一个常用的功能没有提供:索引器!于是我们再加上:

使用ConfigurationManager来写自己的配置文件        public MailPluginElement this[int index]
        }

那么ConfigurationElementCollection告一段落了,现在就是把这些东西塞进ConfigurationSection了:

使用ConfigurationManager来写自己的配置文件    public sealed class MailSection : ConfigurationSection
    }

注意这里的ConfigurationProperty这个Attribute,里面的字符串就是你在配置节里的那个element group节点。当然如果你想省事的话你可以定义为"",这样上面的配置文件就变为:

使用ConfigurationManager来写自己的配置文件<MailSettings>
使用ConfigurationManager来写自己的配置文件      
<add name="Server" value="" />
使用ConfigurationManager来写自己的配置文件      
<add name="Title" value="" />
使用ConfigurationManager来写自己的配置文件      
<add name="Body" value="" />
使用ConfigurationManager来写自己的配置文件  
</MailSettings>

最后便是如何使用了:

使用ConfigurationManager来写自己的配置文件        public string GetConfigValue(string name)
        }

相关文章: