读写ASP.NET web.config
如果你需要读写ASP.NET web.config. 请参考System.Web.Configuration.
在具体写代码以前,请先引用 System.Data, System.Collection,System.Web.Configuration,System.ComponetModule.
写入:
Configuration chapter = WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath);
if (chapter != null)
{
AppSettingsSection cfgHandler = chapter.GetSection("appSettings") as AppSettingsSection;
ConfigHander handler = new ConfigHander();
handler.FirstName = "Gary";
handler.LastName = "Yang";
handler.SectionInformation.ForceSave = true;
cfgHandler.Settings.Add("Gary", "GaryYang");
chapter.Save();
}
if (chapter != null)
{
AppSettingsSection cfgHandler = chapter.GetSection("appSettings") as AppSettingsSection;
ConfigHander handler = new ConfigHander();
handler.FirstName = "Gary";
handler.LastName = "Yang";
handler.SectionInformation.ForceSave = true;
cfgHandler.Settings.Add("Gary", "GaryYang");
chapter.Save();
}
如果你想以对象的形式添加到web.config中,你需要实现相对的类:
这其实是因为.Net Framework提供了IConfigurationSectionHandler接口.
public class ConfigHander : ConfigurationSection
{
[ConfigurationProperty("LastName", IsRequired = false, DefaultValue = "NotGiven")]
public string LastName
{
get {
return (string)base["LastName"];
}
set
{
base["LastName"] = value;
}
}
[ConfigurationProperty("FirstName", IsRequired = false, DefaultValue = "NotGiven")]
public string FirstName
{
get
{
return (string)base["FirstName"];
}
set
{
base["FirstName"] = value;
}
}
public ConfigHander()
{ }
}
{
[ConfigurationProperty("LastName", IsRequired = false, DefaultValue = "NotGiven")]
public string LastName
{
get {
return (string)base["LastName"];
}
set
{
base["LastName"] = value;
}
}
[ConfigurationProperty("FirstName", IsRequired = false, DefaultValue = "NotGiven")]
public string FirstName
{
get
{
return (string)base["FirstName"];
}
set
{
base["FirstName"] = value;
}
}
public ConfigHander()
{ }
}
更多资料: http://www.cnblogs.com/agassi001/archive/2008/01/02/1023811.html
自定义.NET应用程序配置节实例(WEB.CONFIG写自己的XML配置)!
http://www.cnblogs.com/xiazhi33/articles/945429.html