

| 自定义配置节处理实现个性化web.config | ★ | |
| 自定义配置节处理实现个性化web.config | |
作者:佚名 文章来源:不详 点击数: 更新时间:2006-8-10 22:16:22 ![]() | |
|
<!--Sample.ASPx--> private void Page_Load(object sender, System.EventArgs e) { this.tbName = ConfigurationSettings.AppSettings[“AppName“]; } <!--web.config--> <configuration> <appSettings> <add key="AppName" value="MyApplication" /> </appSettings> ... ... 对于ConfigurationSettings类有个方法GetConfig(string sectionName)可以访问任何配置元素,对于以上例子,可如此使用: <!--Sample.ASPx--> private void Page_Load(object sender, System.EventArgs e) { object settings = ConfigurationSettings.GetConfig(“appSettings“); NameValueCollection nvc = settings as NameValueCollection; if (nvc != null) { string val = (string)nvc[“AppName“]; this.tbName = val; } } 可见GetConfig()方法返回了一个配置处理的对象,转换成NameValueCollection的实例后,可以访问到该section内的内容了。其实对于配置文件检索有背后的处理程序实现,同时我们可以看到在web.config,或machine.config中看到对于处理程序的声明,如: <!--web.config--> <configuration> <configSections> <section name="mySection" type="Chagel.Configration.Settings, Configuration" /> </configSections> <mySection> <AppName> MyApplication</AppName> </mySection> ... ... 以上声明了一个mySection元素,并在configSections中声明了该配置的处理程序类名为Chagel.Configration.Settings,Configuration为程序集名称。接下来我们可以通过一个实现System.Configuration.IConfigurationSectionHandler接口的类来处理该配置元素,如: <!--Settings.cs--> using Chagel.Configration.Data; namespace Chagel.Configration { public class Settings:IConfigurationSectionHandler { //实现该接口的Create方法 public object Create(object parent, object input, XMLNode node) { Data data = new Data(); foreach(XMLNode xn in node.ChildNodes) { switch(xn.Name) { case("appName"): data.AppName = xn.InnerText; break; case("appVer"): data.AppVer = xn.InnerText; break; ... ... }//switch end }//foreach end return data; }//method end } } IConfigurationSectionHandler 接口只有一种方法,每当发现注册到处理程序的配置节时,都会在节处理程序上调用 Create 方法,我们实现的类返回一个Data类的实例,该类是一个专门的数据集,代码如下: <!--Data.cs--> namespace Chagel.Configration.Data { public class Data { public Data() { } public string AppName;//程序名称 public string AppVer;//程序版本 public string AppAuthor;//程序作者 ... ... } } 至此,现在可以读取配置元素值了,如: <!--Sample1.ASPx--> private void Page_Load(object sender, System.EventArgs e) { Data data; data = ConfigurationSettings.GetConfig("mySection") as Data; this.tbName.Text = data.AppName; } 到此我们通过实现一个类支持 IConfigurationSectionHandler 接口来对自定义节进行处理,完成对自定义节的读取。当然我们仍可以直接声明系统的处理程序(System.Configuration.NameValueFileSectionHandler)重用与appSettings一样的类。 |
|
| 文章录入:残月 责任编辑:残月 | |
| 【字体:小 大】【发表评论】【加入收藏】【告诉好友】【打印此文】【关闭窗口】 | |