如果你需要讀寫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();
}
如果你想以對象的形式添加到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()
{ }
}
更多資料: http://www.cnblogs.com/agassi001/archive/2008/01/02/1023811.html
自訂.NET應用程式配置節執行個體(WEB.CONFIG寫自己的XML配置)!
http://www.cnblogs.com/xiazhi33/articles/945429.html