最近是遇到了一个需求,需要自定义WebConfig节点,然后进行读取,网上有很多博客,写的非常好,但是笔者在实现的过程中还是遇到了点问题,现在写一篇文章来总结下。
首先推荐大家看http://www.cnblogs.com/huc87/archive/2009/05/06/1450981.html,笔者就是照着这篇blog来完成自己的demo。先把demo贴出来
大家一定要注意ConfigSections一定要写在Configuration里面第一个元素的位置,然后有下划线的地方,一定要把命名空间写全,包括程序集名。其实注意着几点就ok了,剩下的照着上面推荐的博客完全可以完成。
下面是完整的Demo
App.Config
<?xml version=
"1.0"
encoding=
"utf-8"
?>
<configuration>
<configSections>
<sectionGroup name=
"JobList"
>
<section name=
"Job"
type=
"Demo10.MyConfigHandler,Demo10"
/>
</sectionGroup>
</configSections>
<startup>
<supportedRuntime version=
"v4.0"
sku=
".NETFramework,Version=v4.5"
/>
</startup>
<JobList>
<Job>
<add key=
"Url"
value=
"http://www.baidu.com"
/>
<add key=
"Hour"
value=
"10"
/>
<add key=
"Minute"
value=
"20"
/>
</Job>
</JobList>
</configuration>
|
MyConfigHandler.CS
using System; using System.Collections.Generic; using System.Collections.Specialized; using System.Configuration; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Demo10 { public class MyConfigHandler:IConfigurationSectionHandler { public MyConfigHandler() { } public object Create(object parent, object configContext, System.Xml.XmlNode section) { NameValueCollection configs; NameValueSectionHandler baseHandler=new NameValueSectionHandler(); configs = (NameValueCollection) baseHandler.Create(parent, configContext, section); return configs; } } }
按 Ctrl+C 复制代码