[c#] App.Config change value

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?

This question is related to c# app-config

The answer is


when use "ConfigurationUserLevel.None" your code is right run when you click in nameyourapp.exe in debug folder. .
but when your do developing app on visual stdio not right run!! because "vshost.exe" is run.

following parameter solve this problem : "Application.ExecutablePath"

try this : (Tested in VS 2012 Express For Desktop)

Configuration config = ConfigurationManager.OpenExeConfiguration(Application.ExecutablePath);
config.AppSettings.Settings["PortName"].Value = "com3";
config.Save(ConfigurationSaveMode.Minimal);

my english not good , i am sorry.


In addition to the answer by fenix2222 (which worked for me) I had to modify the last line to:

config.Save(ConfigurationSaveMode.Modified);

Without this, the new value was still being written to the config file but the old value was retrieved when debugging.


For a .NET 4.0 console application, none of these worked for me. So I modified Kevn Aenmey's answer as below and it worked:

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

    ConfigurationManager.RefreshSection("appSettings");
}

Only the first line is different, constructed upon the actual executing assembly.


To update entries other than appsettings, simply use XmlDocument.

public static void UpdateAppConfig(string tagName, string attributeName, string value)
{
    var doc = new XmlDocument();
    doc.Load(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);
    var tags = doc.GetElementsByTagName(tagName);
    foreach (XmlNode item in tags)
    {
        var attribute = item.Attributes[attributeName];
        if (!ReferenceEquals(null, attribute))
            attribute.Value = value;
    }
    doc.Save(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);
}

This is how you call it:

Utility.UpdateAppConfig("endpoint", "address", "http://localhost:19092/NotificationSvc/Notification.svc");

Utility.UpdateAppConfig("network", "host", "abc.com.au");

This method can be improved to cater for appSettings values as well.


    private static string GetSetting(string key)
    {
        return ConfigurationManager.AppSettings[key];
    }

    private static void SetSetting(string key, string value)
    {
        Configuration configuration =
            ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
        configuration.AppSettings.Settings[key].Value = value;
        configuration.Save(ConfigurationSaveMode.Full, true);
        ConfigurationManager.RefreshSection("appSettings");
    }

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.


That worked for me in WPF application:

string configPath = Path.Combine(System.Environment.CurrentDirectory, "YourApplication.exe");
Configuration config = ConfigurationManager.OpenExeConfiguration(configPath);
config.AppSettings.Settings["currentLanguage"].Value = "En";
config.Save();

Thanks Jahmic for the answer. Worked properly for me.

another useful code snippet that read the values and return a string:

public static string ReadSetting(string key)
    {
        System.Configuration.Configuration cfg = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
        System.Configuration.AppSettingsSection appSettings = (System.Configuration.AppSettingsSection)cfg.GetSection("appSettings");
        return appSettings.Settings[key].Value;

    }