update web.config custom values in asp.net

Here I am describing about a solution for how to update web.config custom values in asp.net?. Couple of days back I was looking for  update some values in the web,config through c# code.Here I am getting it done using Xpath. If you want to update the values which is there in appsettings there are many easy way to do that . What if you want to update something other than appsettings. Let’s have a look.

Here Below I am giving a sample  web.config file.In this I want to update the value which is in <string > </string>.

       <setting name="Employees" serializeAs="Xml">
          <ArrayOfString xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">

Here I am using xpath for getting this functionality done.

Solution given below.

 XmlTextReader reader = 
    new XmlTextReader(HttpContext.Current.Server.MapPath("~/web.config"));
    XmlDocument doc = new XmlDocument();
    XmlNode oldCd;
    XmlElement root = doc.DocumentElement;
    oldCd = root.SelectSingleNode("/configuration/applicationSettings/projectName.Properties.Settings/setting[@name='Employees']/value/ArrayOfString");
    XmlElement newCd = doc.CreateElement("string");
    newCd.InnerXml = "00001;abc;222;pwd";
    root.SelectNodes("/configuration/applicationSettings/ProjectName.Properties.Settings/setting[@name='Employees']/value/ArrayOfString").Item(0).RemoveChild(oldCd.ChildNodes[i]);// get the correct child if you have multiple
    //save the output to a file


Posted in

Leave a Reply

Your email address will not be published. Required fields are marked *