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>.

<configuration> 
 <applicationSettings>
    <ProjectName.Properties.Settings>
       <setting name="Employees" serializeAs="Xml">
        <value>
          <ArrayOfString xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
            <string>000001;PSWD;xxx;Password</string>           
          </ArrayOfString>
        </value>
      </setting>
    </ProjectName.Properties.Settings>
  </applicationSettings>
</configuration>

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();
    doc.Load(reader);
    reader.Close();
    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
    root.SelectNodes("/configuration/applicationSettings/ProjectName.Properties.Settings/setting[@name='Employees']/value/ArrayOfString").Item(0).AppendChild(newCd);
                            
    //save the output to a file
    doc.Save(HttpContext.Current.Server.MapPath("~/web.config"));

thanks;

Posted in

Leave a Reply

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