Thursday, November 29, 2012

C# Windows Application Update app.config file

In the Post C# Windows Application Reading app.config file, we saw on how to read the key values in the App.config file, there are situations where we will have to update the values in the app.config file dynamically from within the application. 

In this post we shall see on how to update the values in the app.config file from the application.



App.config file before the update.

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <appSettings>
    <add key="TestKey" value="OriginalTestValue" />
  </appSettings>

</configuration>

Code to Update the app.config file

XmlDocument
XmlDoc = new XmlDocument();
XmlDoc.Load(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);
XmlNode keyNode = XmlDoc.SelectSingleNode("/configuration/appSettings/add");
keyNode.Attributes[1].Value = "UpdatedTestValue";

XmlDoc.Save(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);

App.config file after the update.

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <appSettings>
    <add key="TestKey" value="UpdatedTestValue" />
  </appSettings>
</configuration>


Add a reference to the System.Xml Namespace, since we are parsing the app.Config file.
using System.Xml;

Search other Products:
Flipkart.com

No comments: