類似RemotingConfiguration.Configure("SyncAsync.exe.config");
applicationname.exe.config 你可以通過編程的方式,使用SYSTEM.CONFIGURATION名稱空間從
XML .config檔案中擷取應用程式設定資訊。
例子代碼:
<appSettings>
<!--add key="constring" value="Server=zsl;uid=sa;pwd=;DataBase=OA"-->
<add key="constring" value="Provider=sqloledb;Data Source=zsl;Initial Catalog=OA;User Id=sa;Password=;"/>
</appSettings>
ConfigurationSettings.AppSettings["constring"].ToString()
只是在程式開始時驗證,另外在檔案中含有指令檔,CDATA檔案如何解決?
web.config檔案自訂配置節的使用方法- -
[轉載]web.config檔案自訂配置節的使用方法
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介面來讀取配置