How edit the appsettings section in app.config file in program running

With this code you can edit your app.config file. If you use the ConfigurationManager class only change the value in memory. With this sample you can change the file.

In the next code I edit the app.config file with the XmlDocument class and refresh all the new values. The code is commented.

using System.Xml;
using System.Configuration;

public class EditorAppSettings{

    public static void EditAppSettings(string key, string value){
        XmlDocument xmlDoc = new XmlDocument();
        //travel for all the xml 
        foreach (XmlElement element in xmlDoc.DocumentElement)
            if (element.Name.Equals("appSettings"))
                //travel for the appSettings node
                foreach (XmlNode node in element.ChildNodes)
                    //to compare with the key and edit for the new value
                        if (node.Attributes[0].Value == key)
                        node.Attributes[1].Value = value;
        //save the file
        //refresh the new values in memory

//in use


View all posts by