Article: ASP. NET program to dynamically modify the settings item in Web. config (background CS code)
Friends can test themselves, I have no problem here, turtle a morning's problem finally solved
Using System;
Using System.Collections;
Using System.ComponentModel;
Using System.Data;
Using System.Drawing;
Using System.Web;
Using System.Web.SessionState;
Using System.Web.UI;
Using System.Web.UI.WebControls;
Using System.Web.UI.HtmlControls;
Using System.Xml;
Namespace WebApplication1
{
<summary>
Summary description for WebForm1.
</summary>
public class WebForm1:System.Web.UI.Page
{
protected System.Web.UI.WebControls.TextBox TextBox1;
protected System.Web.UI.WebControls.DropDownList DropDownList1;
protected System.Web.UI.WebControls.Button Button1;
Public WebForm1 ()
{
Page.Init + = new System.EventHandler (Page_Init);
}
private void Page_Load (object sender, System.EventArgs e)
{
if (! Page.IsPostBack)
{
Open a file (assuming the web. Config in the root directory)
String Filename=server.mappath ("/") + @ "\web.config";
XmlDocument xmldoc= new XmlDocument ();
XmlDoc. Load (filename);
XmlNodeList Topm=xmldoc. Documentelement.childnodes;
foreach (XmlElement element in topm)
{
if (element. Name.tolower () = = "appsettings")
{
XmlNodeList _node=element. ChildNodes;
if (_node. Count >0)
{
DropDownList1.Items.Clear ();
foreach (XmlElement el in _node)
{
DropDownList1.Items.Add (el. attributes["Key"]. INNERXML);
}
}
}
}
}
}
private void Page_Init (object sender, EventArgs e)
{
InitializeComponent ();
}
#region Web Form Designer generated code
<summary>
Required method for Designer support-do not modify
The contents of this method with the Code editor.
</summary>
private void InitializeComponent ()
{
This. Button1.Click + = new System.EventHandler (this. Button1_Click);
This. Load + = new System.EventHandler (this. Page_Load);
}
#endregion
private void Button1_Click (object sender, System.EventArgs e)
{
String Filename=server.mappath ("/") + @ "\web.config";
XmlDocument xmldoc= new XmlDocument ();
XmlDoc. Load (filename);
xmlnodelist Topm=xmldoc. Documentelement.childnodes;
foreach (XmlElement element in topm)
{
if (element. Name.tolower () = = "appsettings")
{
XmlNodeList _node=element. ChildNodes;
if (_node. Count >0)
{
foreach (XmlElement el in _node)
{
if (el. attributes["Key"]. Innerxml.tolower () ==this. DropDownList1.SelectedItem.Value.ToLower ())
{
El. attributes["Value"]. Value=this. TextBox1.Text;
}
}
}
}
}
xmldoc. Save (filename);
}
}
}