Modifying the web.config file from a windows application


In this article, we are going to see how you can modify the web.config file of an asp.net application using a windows based application in C#. We are going to use xml to load the web.config file and modify the appSettings section of it.

In this article, we are going to see how we can modify the web.config file of an asp.net application using a windows based application in C#.

In this code sample, we are following the below steps:

1.First get the path where the web.config file is located on our system. Here we are updating the config file which is located in "c:\inetpub\WWWRoot\WebSite1" location.
2.Then using XmlDocument class load the file in memory.
3.Get the reference to the appSettings section, with key=ipaddress.
4.if we can find the node with above key, then change its value to the value entered by the user in the textbox and save back the file.
5.In case of any exceptions, display it in a messagebox.


//Get the path of the web.config file of the application which you want to modify
string filename = @"c:\inetpub\WWWRoot\WebSite1\Web.Config";
try
{
System.Xml.XmlDocument Doc = new System.Xml.XmlDocument();
//Load the config file in memory.
Doc.Load(filename);
System.Xml.XmlElement Root = Doc.DocumentElement;

//Get the node which contains the appsettings section with key "ipaddress"
string xpath = "appSettings/add[@key='ipaddress']";
System.Xml.XmlNode xnode = Root.SelectSingleNode(xpath);
if (xnode != null)
{
//update the key "ipaddress" with the value entered in the textbox by the user.
xnode.Attributes["value"].Value = txtIpAddress.Text;
}
//Save the config file.
Doc.Save(filename);
}
catch (System.Exception ex)
{
//Incase of any exception, display it in a message box.
MessageBox.Show(ex.Message);
}


Article by Vaishali Jain
Miss. Jain Microsoft Certified Technology Specialist in .Net(Windows and Web Based application development)

Follow Vaishali Jain or read 127 articles authored by Vaishali Jain

Comments

No responses found. Be the first to comment...


  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:
    Email: