[c#] 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?

This question is related to c# .net appsettings configurationmanager settings

The answer is


Try adding this after your save call.

ConfigurationManager.RefreshSection( "appSettings" );

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);

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.


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);
}

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.


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>

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.


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


Examples related to c#

How can I convert this one line of ActionScript to C#? Microsoft Advertising SDK doesn't deliverer ads How to use a global array in C#? How to correctly write async method? C# - insert values from file into two arrays Uploading into folder in FTP? Are these methods thread safe? dotnet ef not found in .NET Core 3 HTTP Error 500.30 - ANCM In-Process Start Failure Best way to "push" into C# array

Examples related to .net

You must add a reference to assembly 'netstandard, Version=2.0.0.0 How to use Bootstrap 4 in ASP.NET Core No authenticationScheme was specified, and there was no DefaultChallengeScheme found with default authentification and custom authorization .net Core 2.0 - Package was restored using .NetFramework 4.6.1 instead of target framework .netCore 2.0. The package may not be fully compatible Update .NET web service to use TLS 1.2 EF Core add-migration Build Failed What is the difference between .NET Core and .NET Standard Class Library project types? Visual Studio 2017 - Could not load file or assembly 'System.Runtime, Version=4.1.0.0' or one of its dependencies Nuget connection attempt failed "Unable to load the service index for source" Token based authentication in Web API without any user interface

Examples related to appsettings

Getting value from appsettings.json in .net core Automatically set appsettings.json for dev and release environments in asp.net core? Get ConnectionString from appsettings.json instead of being hardcoded in .NET Core 2.0 App AppSettings get value from .config file Opening the Settings app from another app ConfigurationManager.AppSettings - How to modify and save? How to check if an appSettings key exists? Reading settings from app.config or web.config in .NET

Examples related to configurationmanager

SCCM 2012 application install "Failed" in client Software Center AppSettings get value from .config file ConfigurationManager.AppSettings - How to modify and save? How to get the values of a ConfigurationSection of type NameValueSectionHandler How to check if an appSettings key exists? How to find path of active app.config file?

Examples related to settings

How to configure "Shorten command line" method for whole project in IntelliJ Error: Module not specified (IntelliJ IDEA) Instant run in Android Studio 2.0 (how to turn off) How do I open phone settings when a button is clicked? Google Chrome: This setting is enforced by your administrator maven command line how to point to a specific settings.xml for a single command? Django: ImproperlyConfigured: The SECRET_KEY setting must not be empty Python: How would you save a simple settings/config file? How to set my phpmyadmin user session to not time out so quickly? Setting DEBUG = False causes 500 Error