實作ConfigurationElement
一般來說我們若有某些共用的屬性是供全域使用的話會在組態檔增加一個Appsetting設定例:ConfiguationManager.Appsetting["test"]
但此種寫法,僅適合單一值,若此設定需設定多個欄位值的話,我們可以藉由實作ConfiguationElement來實現
程式碼:
1.實作ConfiguationElement
public class KimReportServerElement : ConfigurationElement
{
[ConfigurationProperty("url", IsRequired = true)]
public string Url
{
get
{
string result = (string)base["url"];
if (result == String.Empty)
throw new ConfigurationErrorsException("<reportServer>的url屬性不得為空字串");
return result;
}
set
{
base["url"] = value;
}
}
[ConfigurationProperty("username")]
public string Username
{
get
{
return (string)base["username"];
}
set
{
base["username"] = value;
}
}
[ConfigurationProperty("password")]
public string Password
{
get
{
return (string)base["password"];
}
set
{
base["password"] = value;
}
}
}
2.實作System.Configuration.ConfigurationSection
public class KimSection : System.Configuration.ConfigurationSection
{
[ConfigurationProperty("KimReportServer")]
public KimReportServerElement KimReportServer
{
get
{
return (KimReportServerElement)base["KimReportServer"];
}
}
}
3.組態設定
<configSections>
<section name="Kim" type="Kim.Configuration.KimSection,Kim.Configuration"/>
</configSections>
<Kim>
<KimReportServer username="阿銘" password="123456" url="http://blog.yam.com/slkim"/>
</Kim>
4.程式測試
KimSection kimObj = System.Configuration.ConfigurationManager.GetSection("Kim") as KimSection;
Response.Write("Username:" + kimObj.KimReportServer.Username + "<br>");
Response.Write("Password:" + kimObj.KimReportServer.Password + "<br>");
Response.Write("Url:" + kimObj.KimReportServer.Url + "<br>");
參考文件
http://msdn.microsoft.com/zh-tw/library/system.configuration.configurationsection.aspx