asp.net(C#)动态修改Web.config文件

来源:互联网 发布:淘宝怎样开通花呗 编辑:程序博客网 时间:2024/05/04 16:44
 
Web.config文件假设有如下需要管理的配置信息: 实现的c#核心代码: 一、将Web.config中的相关信息读入TextBox private void Page_Load(object sender, System.EventArgs e) { if(!Page.IsPostBack) { //将Web.config中的相关值填入TextBox this.txtTitle.Text=System.Configuration.ConfigurationSettings.AppSettings["SiteTitle"]; this.txtUrl.Text=System.Configuration.ConfigurationSettings.AppSettings["SiteUrl"]; this.txtLogo.Text=System.Configuration.ConfigurationSettings.AppSettings["SiteLogo"]; this.txtBanner.Text=System.Configuration.ConfigurationSettings.AppSettings["SiteBanner"]; this.txtEmail.Text=System.Configuration.ConfigurationSettings.AppSettings["SiteEmail"]; } } 二、将修改后的内容写入Web.config private void btnSave_Click(object sender, System.EventArgs e) { string filename=Server.MapPath("web.config"); string KeyName;//键名称 XmlDocument xmldoc= new XmlDocument(); try { xmldoc.Load(filename); } catch { Response.Write(" "); return; } XmlNodeList DocdNodeNameArr=xmldoc.DocumentElement.ChildNodes;//文档节点名称数组 foreach(XmlElement DocXmlElement in DocdNodeNameArr) { if(DocXmlElement.Name.ToLower()=="appsettings")//找到名称为 appsettings 的节点 { XmlNodeList KeyNameArr=DocXmlElement.ChildNodes;//子节点名称数组 if ( KeyNameArr.Count >0 ) { foreach(XmlElement xmlElement in KeyNameArr) { KeyName=xmlElement.Attributes["key"].InnerXml;//键值 switch(KeyName) { case "SiteTitle": xmlElement.Attributes["value"].Value=this.txtTitle.Text; break; case "SiteUrl": xmlElement.Attributes["value"].Value=this.txtUrl.Text; break; case "SiteLogo": xmlElement.Attributes["value"].Value=this.txtLogo.Text; break; case "SiteBanner": xmlElement.Attributes["value"].Value=this.txtBanner.Text; break; case "SiteEmail": xmlElement.Attributes["value"].Value=this.txtEmail.Text; break; } } } } } try { xmldoc.Save(filename); Response.Write(" "); } catch { Response.Write(" "); return; } }