web.config文件自定義配置節的使用方法的一個簡單例子
2024-07-21 02:07:08
供稿:網友
web.config文件自定義配置節的使用方法的一個簡單例子
用來演示的程序名為myapp,namespace也是myapp
1。編輯web.config文件
添加以下內容,聲明一個section
<configsections>
<section name="appconfig" type="myapp.appconfig, myapp" />
</configsections>
聲明了一個叫appconfig的section
2。編輯web.config文件
添加以下內容,加入一個section
<appconfig>
<add key="connectionstring" value="this is a connectionstring" />
<add key="usercount" value="199" />
</appconfig>
這個section包括兩個 key
3。從iconfigurationsectionhandler派生一個類,appconfig
實現create方法,代碼如下
public class appconfig : iconfigurationsectionhandler
{
static string m_connectionstring = string.empty;
static int32 m_usercount = 0;
public static string connectionstring
{
get
{
return m_connectionstring;
}
}
public static int32 usercount
{
get
{
return m_usercount;
}
}
static string readsetting(namevaluecollection nvc, string key, string defaultvalue)
{
string thevalue = nvc[key];
if(thevalue == string.empty)
return defaultvalue;
return thevalue;
}
public object create(object parent, object configcontext, xmlnode section)
{
namevaluecollection settings;
try
{
namevaluesectionhandler basehandler = new namevaluesectionhandler();
settings = (namevaluecollection)basehandler.create(parent, configcontext, section);
}
catch
{
settings = null;
}
if ( settings != null )
{
m_connectionstring = appconfig.readsetting(settings, "connectionstring", string.empty);
m_usercount = convert.toint32(appconfig.readsetting(settings, "usercount", "0"));
}
return settings;
}
}
我們把所有的配置都映射成相應的靜態成員變量,并且是寫成只讀屬性,這樣程序通過
類似appconfig.connectionstring就可以訪問,配置文件中的項目了
4。最后還要做一件事情
在global.asax.cs中的application_start中添加以下代碼
system.configuration.configurationsettings.getconfig("appconfig");
這樣在程序啟動后,會讀取appconfig這個section中的值,系統會調用你自己實現的iconfigurationsectionhandler接口來讀取配置