您的位置:首页 > 其它

自定义web.config节点 实现ConfigurationElement,ConfigurationSec

2009-11-03 14:35 337 查看
//

using System;
using System.Data;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;

/// <summary>
/// Summary description for MyElement
/// </summary>
public class MyElement : ConfigurationElement
{
public MyElement()
{
//
// TODO: Add constructor logic here
//
}
[ConfigurationProperty("userName",IsRequired=true)]
public string UserName
{
get { return (string)this["userName"]; }
set { this["userName"] = value; }
}
[ConfigurationProperty("userPwd")]
public string UserPwd
{
get { return (string)this["userPwd"]; }
set { this["userPwd"] = value; }
}
}
public class MyElementCollection : ConfigurationElementCollection
{

public MyElementCollection()
{
MyElement element = CreateNewElement() as MyElement;
}
protected override ConfigurationElement CreateNewElement()
{
return new MyElement();
}

protected override object GetElementKey(ConfigurationElement element)
{
return ((MyElement)element).UserName;
}
protected override void BaseAdd(ConfigurationElement element)
{
base.BaseAdd(element,false);
}
public void Add(MyElement element)
{
BaseAdd(element);
}
}
public class MyConfigSection : ConfigurationSection
{

MyElement element;

public MyConfigSection()
{
element = new MyElement();
}

[ConfigurationProperty("files")]
public MyElementCollection FileTypes
{
get
{
MyElementCollection types = (MyElementCollection)base["files"];
return types;
}
}

protected override void DeserializeSection(System.Xml.XmlReader reader)
{
base.DeserializeSection(reader);
}

protected override string SerializeSection(ConfigurationElement parentElement, string name, ConfigurationSaveMode saveMode)
{
return base.SerializeSection(parentElement, name, saveMode);
}

}

//Web.config

<section name="MyConfigS" type="MyConfigSection"/>
</configSections>
//Test

protected void Button1_Click(object sender, EventArgs e)
{
Configuration config = WebConfigurationManager.OpenWebConfiguration("~");
MyConfigSection files = config.Sections["MyConfigS"] as MyConfigSection;
MyElement obj = new MyElement();
obj.UserName = "sdf";
obj.UserPwd = "sdf";
files.FileTypes.Add(obj);
config.Save();
}
/article/5452938.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: