How to Save Configuation in app.config in C# Winforms

30,478

Solution 1

In ASP.NET:

Configuration config = WebConfigurationManager.OpenWebConfiguration(null);
AppSettingsSection app = config.AppSettings;
app.Settings.Add("x", "this is X");
config.Save(ConfigurationSaveMode.Modified);

In WinForms:

Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
AppSettingsSection app = config.AppSettings;
app.Settings.Add("x", "this is X");
config.Save(ConfigurationSaveMode.Modified);

Solution 2

I know you specifically asked for WinForms solution, but this might help some others. For a .NET 4.0 console application, none of these worked for me. So I used the following 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");
}
Share:
30,478
monkey_boys
Author by

monkey_boys

Nothing I' am alone boy and be live for my dream Nothing about me Csharp Snippet Piyanut Khajohnsubdee King Mongkut's University of Technology North Bangkok Google's Profile programmatically : Dynamic Style ปิยะณัฐ ขจรทรัพย์ดี

Updated on July 29, 2020

Comments

  • monkey_boys
    monkey_boys over 3 years

    Can someone give me an example of how to save a key/value in app.config using C# and WinForms?

  • monkey_boys
    monkey_boys almost 15 years
    why i cant see ConfigurationManager class
  • monkey_boys
    monkey_boys almost 15 years
    when i open app.config it not write "x" and "this is x"
  • Kris-I
    Kris-I over 14 years
    add : using System.Configuration; in the using section
  • Wout
    Wout over 11 years
    @monkey_boys: When running e.g. a win forms application from VS, the relevant .config file to look for is: <My application>.vshost.exe.config, so if you were looking in <My application>.exe.config then you don't see any change.
  • Azimuth
    Azimuth over 9 years
    @AshkanMobayenKhiabani no, it adds a new comma-separated value.