98

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?

radbyx
  • 9,352
  • 21
  • 84
  • 127
Houman
  • 64,245
  • 87
  • 278
  • 460
  • 1
    possible duplicate of [Best practice to save application settings in a Windows application](http://stackoverflow.com/questions/453161/best-practice-to-save-application-settings-in-a-windows-application) – Richard Mar 11 '11 at 15:36
  • Refer this: http://stackoverflow.com/questions/453161/best-practice-to-save-application-settings-in-a-windows-application – Kumar Mar 11 '11 at 15:31
  • I actually didn't want to use Settings.settings as suggested there. But now I think the way I use it, is not the correct aproach after all, since its saving the values as Application settings rather than usersettings... – Houman Mar 11 '11 at 16:04
  • 3
    It will be in the folder that the executable is located in. So if you running it from Visual Studio under Debug it will be in the Debug folder of your project. – Justin Mar 11 '11 at 17:32
  • 1
    Ditto what Justin said. And if you are running from Visual Studio, it will OVERWRITE the .config file in the Debug folder of your project each time you re-run your application. – Welton v3.62 May 15 '13 at 14:35
  • I find this in some jQuery code that looks bizarre to me: var calendar_src = '/@ConfigurationManager.AppSettings["ThisApp"]/Content/Images/calendar_icon_blue.png'; Why not just var calendar_src = 'Content/Images/calendar_icon_blue.png'; ? – B. Clay Shannon-B. Crow Raven Aug 13 '13 at 21:55
  • 1
    http://geekswithblogs.net/akraus1/archive/2006/01/04/64871.aspx hope this help :) – Thomas Mar 14 '14 at 09:17

9 Answers9

114

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

Wahid Bitar
  • 13,776
  • 13
  • 78
  • 106
  • 4
    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 http://vbcity.com/forums/t/152772.aspx – yu yang Jian Jul 26 '17 at 02:10
  • 1
    Works well in .NET 6 Winforms – Mariusz Jun 29 '22 at 10:46
  • I know this is an ancient question but when I use this in a Webforms app to get appsettings in my Webconfig, it works fine on my local instance, but on the server I get a null reference exception at configFile.Save(ConfigurationSaveMode.Modified); I've checked config for null before, and it's not null, and furthermore it approriately gets and sets the settings object for the given key, so I'm failing to understand how the null reference exception is showing up... – Levi Wallach Feb 27 '23 at 18:26
74

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.

Marek
  • 2,419
  • 6
  • 34
  • 38
  • 4
    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 node – downwitch Jul 20 '14 at 04:56
43

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>
Stephan Bauer
  • 9,120
  • 5
  • 36
  • 58
Tom Wilson
  • 698
  • 6
  • 9
  • 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: ? – Pranesh Janarthanan Aug 01 '21 at 17:19
26

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.

Dan
  • 12,808
  • 7
  • 45
  • 54
  • 1
    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(); – Houman Mar 11 '11 at 16:08
  • 1
    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 – Dan Mar 11 '11 at 16:35
  • 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. – RyanfaeScotland Apr 10 '18 at 15:20
  • I can't believe I've been looping through an XML file all this time. Thanks a lot for this useful tip! – Smitty-Werben-Jager-Manjenson Jan 24 '19 at 14:23
24

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);
Community
  • 1
  • 1
Omid S.
  • 731
  • 7
  • 15
10

Try adding this after your save call.

ConfigurationManager.RefreshSection( "appSettings" );
Justin
  • 4,002
  • 2
  • 19
  • 21
  • 1
    This is particularly important if you're writing then reading to the same appSetting in quick succession. – Trevor Nov 03 '15 at 19:29
6

Remember that ConfigurationManager uses only one app.config - one that is in startup project.

If you put some app.config to a solution A and make a reference to it from another solution B then if you run B, app.config from A will be ignored.

So for example unit test project should have their own app.config.

Jason Sturges
  • 15,855
  • 14
  • 59
  • 80
doubleloop
  • 61
  • 1
  • 2
2

I think the problem is that in the debug visual studio don't use the normal exeName.

it use indtead "NameApplication".host.exe

so the name of the config file is "NameApplication".host.exe.config and not "NameApplication".exe.config

and after the application close - it return to the back app.config

so if you check the wrong file or you check on the wrong time you will see that nothing changed.

chmouel kalifa
  • 129
  • 2
  • 11
-2

You can change it manually:

private void UpdateConfigFile(string appConfigPath, string key, string value)
{
     var appConfigContent = File.ReadAllText(appConfigPath);
     var searchedString = $"<add key=\"{key}\" value=\"";
     var index = appConfigContent.IndexOf(searchedString) + searchedString.Length;
     var currentValue = appConfigContent.Substring(index, appConfigContent.IndexOf("\"", index) - index);
     var newContent = appConfigContent.Replace($"{searchedString}{currentValue}\"", $"{searchedString}{newValue}\"");
     File.WriteAllText(appConfigPath, newContent);
}