Search code examples
c#.netappsettingsconfigurationmanagersettings

ConfigurationManager.AppSettings - How to modify and save?


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?


Solution

  • 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.