標籤:style blog http color get 2014
最近是遇到了一個需求,需要自訂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; } }}
namespace Demo10{ class Program { static void Main(string[] args) { object o = ((NameValueCollection) ConfigurationSettings.GetConfig("JobList/Job")); string myWebSiteName = ((NameValueCollection) ConfigurationSettings.GetConfig("JobList/Job"))["Url"]; } }}