我們可以通過用自己的 xml 配置元素來擴充标準的 asp.net 配置設定集,要完成這一功能,我們必須實作繼承system.configuration.configurationsection
類來實作自定義配置節,在1.0中當然也可以通過iconfigurationsectionhandler 接口建立自定義配置節!這裡我們主要學一下通過configurationsection類來實作簡單的配置處理程式.
先看一下在web.config檔案中的配置情況,在這裡有兩個元素,第一個mysection,有兩個屬性user,password,第二個也有兩個屬性element1,和element2。配置比較簡單。
<!--//////////////////////////////////////////////////////////////////////////////////////////////-->
<configsections>
<sectiongroup name="mygroup">
<section name="mysection"
type="configsection"
allowdefinition="everywhere"
allowlocation="true"/>
</sectiongroup>
</configsections>
<mygroup>
<mysection user="使用者" password="密碼">
<element element1="屬性1" element2="屬性2"></element>
</mysection>
</mygroup>
了解配置檔案結構後,我們就需要用繼承自system.configuration.configurationsection的基類來實作簡單的配置類configsection,在2.0中,我們隻需要這一個類就能實作完成配置,下面請看代碼:
using system;
using system.data;
using system.configuration;
using system.web;
using system.web.security;
using system.web.ui;
using system.web.ui.webcontrols;
using system.web.ui.webcontrols.webparts;
using system.web.ui.htmlcontrols;
/// <summary>
/// configsection 的摘要說明
/// </summary>
public class configsection:configurationsection
{
public configsection()
{
//
// todo: 在此處添加構造函數邏輯
}
[configurationproperty("user",defaultvalue="yanghong",isrequired=true)]
public string user
get { return (string)this["user"]; }
set { this["user"] = value; }
[configurationproperty("password",defaultvalue="password",isrequired=true)]
public string password
get { return (string)this["password"]; }
set { this["password"] = value; }
[configurationproperty("element")]
public elementinfo element
get { return (elementinfo)this["element"]; }
set {this["element"] = value; }
}
public class elementinfo : configurationelement
public elementinfo() { }
[configurationproperty("element1", defaultvalue = "element1", isrequired = true)]
public string element1
get { return (string)this["element1"]; }
[configurationproperty("element2",defaultvalue="element2",isrequired=true)]
public string element2
get { return (string)this["element2"]; }
通過下面的代碼就可以獲得在配置檔案中設定的值了
configsection config = (configsection)configurationmanager.getsection("mygroup/mysection");
response.write("使用者名:"+config.user.tostring() + "密碼:" + config.password.tostring() + "元素屬性:" + config.element.element1.tostring() + config.element.element2.tostring());
轉自“:http://www.cnblogs.com/flyyanghong/archive/2007/11/01/945930.html