先看一下在web.config文件中的配置情况,在这里有两个元素,第一个mysection,有两个属性user,password,第二个也有两个属性element1,和element2。配置比较简单。
理解配置文件结构后,我们就需要用继承自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 " ]; }
}
}
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 " ]; }
}
}
通过下面的代码就可以获得在配置文件中设置的值了