App.Config change value

a1204773 picture a1204773 · Jun 22, 2012 · Viewed 156.4k times · Source

This is my App.Config

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

With this code I make the change

lang = "Russian";
private void Main_FormClosing(object sender, FormClosingEventArgs e)
{
     System.Configuration.ConfigurationManager.AppSettings.Set("lang", lang);
}

But it not change. What I'm doing wrong?

Answer

Kevin Aenmey picture Kevin Aenmey · Jun 22, 2012

AppSettings.Set does not persist the changes to your configuration file. It just changes it in memory. If you put a breakpoint on System.Configuration.ConfigurationManager.AppSettings.Set("lang", lang);, and add a watch for System.Configuration.ConfigurationManager.AppSettings[0] you will see it change from "English" to "Russian" when that line of code runs.

The following code (used in a console application) will persist the change.

class Program
{
    static void Main(string[] args)
    {
        UpdateSetting("lang", "Russian");
    }

    private static void UpdateSetting(string key, string value)
    {
        Configuration configuration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
        configuration.AppSettings.Settings[key].Value = value;
        configuration.Save();

        ConfigurationManager.RefreshSection("appSettings");
    }
}

From this post: http://vbcity.com/forums/t/152772.aspx

One major point to note with the above is that if you are running this from the debugger (within Visual Studio) then the app.config file will be overwritten each time you build. The best way to test this is to build your application and then navigate to the output directory and launch your executable from there. Within the output directory you will also find a file named YourApplicationName.exe.config which is your configuration file. Open this in Notepad to see that the changes have in fact been saved.