Search code examples
c#.netapp-config

Add key to App.config programmatically C#


I'm trying to programmatically add and save a key to my App.config file. My code is below, I've seen tons of different examples like this, and mine is not working. I'm trying to add a brand new key, not modify an existing. This is a console application, and I did make sure to add a Reference to System.configuration.

Program.cs

using System;
using System.Linq;
using System.Text;
using System.Configuration;

namespace AddValuesToConfig
{
    class Program
    {
        static void Main(string[] args)
        {

            System.Configuration.Configuration config = System.Configuration.ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

            config.AppSettings.Settings.Add("key1", "value");

            // Save the changes in App.config file.

            config.Save(ConfigurationSaveMode.Modified);

        }
    }
}

App.config

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <appSettings>

    </appSettings>
</configuration>

Solution

  • Most likely you run this code under debugger in Visual Studio. Thing is when you do this, Visual Studio really runs not YourApp.exe, but YourApp.vshost.exe file. That means you are adding your key to YourApp.vshost.exe.config file instead of YourApp.exe.config. Try run without debugger, it should work then.

    EDIT to answer comment below. Topic starter claims that VS does not write even to .vshost.exe.config when debugging, and I thought that is true. However little investigation shows that it DOES write to .vshost.config.exe file, BUT when you stop debugging, it will overwrite contents of your .vshost.exe.config with your .exe.config. So after your debugging session ends, you might think it did not write anything at all. However, if you put breakpoint right after config.Save() statement and open .vshost.exe.config file - you will see changes there.