ConfigurationManager.AppSettings - How to modify and save?

242,455

Solution 1

Perhaps you should look at adding a Settings File. (e.g. App.Settings) Creating this file will allow you to do the following:

string mysetting = App.Default.MySetting;
App.Default.MySetting = "my new setting";

This means you can edit and then change items, where the items are strongly typed, and best of all... you don't have to touch any xml before you deploy!

The result is a Application or User contextual setting.

Have a look in the "add new item" menu for the setting file.

Solution 2

I know I'm late :) But this how i do it:

public static void AddOrUpdateAppSettings(string key, string value)
{
    try
    {
        var configFile = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
        var settings = configFile.AppSettings.Settings;
        if (settings[key] == null)
        {
            settings.Add(key, value);
        }
        else
        {
            settings[key].Value = value;
        }
        configFile.Save(ConfigurationSaveMode.Modified);
        ConfigurationManager.RefreshSection(configFile.AppSettings.SectionInformation.Name);
    }
    catch (ConfigurationErrorsException)
    {
        Console.WriteLine("Error writing app settings");
    }
}

For more information look at MSDN

Solution 3

On how to change values in appSettings section in your app.config file:

config.AppSettings.Settings.Remove(key);
config.AppSettings.Settings.Add(key, value);

does the job.

Of course better practice is Settings class but it depends on what are you after.

Solution 4

Prefer <appSettings> to <customUserSetting> section. It is much easier to read AND write with (Web)ConfigurationManager. ConfigurationSection, ConfigurationElement and ConfigurationElementCollection require you to derive custom classes and implement custom ConfigurationProperty properties. Way too much for mere everyday mortals IMO.

Here is an example of reading and writing to web.config:

using System.Web.Configuration;
using System.Configuration;

Configuration config = WebConfigurationManager.OpenWebConfiguration("/");
string oldValue = config.AppSettings.Settings["SomeKey"].Value;
config.AppSettings.Settings["SomeKey"].Value = "NewValue";
config.Save(ConfigurationSaveMode.Modified);

Before:

<appSettings>
  <add key="SomeKey" value="oldValue" />
</appSettings>

After:

<appSettings>
  <add key="SomeKey" value="newValue" />
</appSettings>

Solution 5

as the base question is about win forms here is the solution : ( I just changed the code by user1032413 to rflect windowsForms settings ) if it's a new key :

Configuration config = configurationManager.OpenExeConfiguration(Application.ExecutablePath); 
config.AppSettings.Settings.Add("Key","Value");
config.Save(ConfigurationSaveMode.Modified);

if the key already exists :

Configuration config = ConfigurationManager.OpenExeConfiguration(Application.ExecutablePath); 
config.AppSettings.Settings["Key"].Value="Value";
config.Save(ConfigurationSaveMode.Modified);
Share:
242,455
Houman
Author by

Houman

I'm a thinker and a dreamer. Love pets but don't have any. I'm a passionate tech entrepreneur.

Updated on January 12, 2020

Comments

  • Houman
    Houman over 4 years

    It might sound too trival to ask and I do the same thing as suggested in articles, yet it doesn't work as expected. Hope someone can point me to the right direction.

    I would like to save the usersettings per AppSettings.

    Once the Winform is closed I trigger this:

    conf.Configuration config = 
               ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
    
    if (ConfigurationManager.AppSettings["IntegrateWithPerforce"] != null)
        ConfigurationManager.AppSettings["IntegrateWithPerforce"] = 
                                               e.Payload.IntegrateCheckBox.ToString();
    else
        config.AppSettings.Settings.Add("IntegrateWithPerforce", 
                                              e.Payload.IntegrateCheckBox.ToString());
    
    config.Save(ConfigurationSaveMode.Modified);
    

    So the first time when the entry doesnt exist yet, it would simply create it, otherwise it would modify the existing entry. However this doesn't save.

    1) What am I doing wrong?

    2) Where am I expecting the usersettings for App settings to be saved again? Is it in the Debug folder or in C:\Documents and Settings\USERNAME\Local Settings\Application Data folder?

  • Houman
    Houman about 13 years
    Adding a Settings.Settings file or using the existing one under Properties/Settings.settings is teh same thing right? In case of using the exsiting one, I would do something like this: Properties.Settings.Default.IntegrateWithPerforce = _integrateCheckBox.Checked; Properties.Settings.Default.Save();
  • Dan
    Dan about 13 years
    Quite possibly. I have always just used seperate files as that has done me well. If that is the case, I have just learned something
  • downwitch
    downwitch almost 10 years
    After looking at three kajillion AppSettings modifications ideas here and abroad, this is the simplest/best, and (crucially) works even if the user destroys the <appSettings> node
  • Trevor
    Trevor over 8 years
    This is particularly important if you're writing then reading to the same appSetting in quick succession.
  • yu yang Jian
    yu yang Jian almost 7 years
    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. --- from vbcity.com/forums/t/152772.aspx
  • RyanfaeScotland
    RyanfaeScotland about 6 years
    Fascinating, if you use this AND the ConfigurationManager then all the settings end up in the App.config file anyway but under different sections. I was expecting 2 different files.
  • Smitty-Werben-Jager-Manjenson
    Smitty-Werben-Jager-Manjenson over 5 years
    I can't believe I've been looping through an XML file all this time. Thanks a lot for this useful tip!
  • Pranesh Janarthanan
    Pranesh Janarthanan almost 3 years
    I have my app deployed in C:, I gave access to the app root folder with Security Users:Fullaccess, but still my application shows an exception that the config file access is denied. Is it better to use a different location like %appdata% to save data and retrieve the same instead of using C: ?
  • Mariusz
    Mariusz almost 2 years
    Works well in .NET 6 Winforms