38

In my app.config I have this section

<appSettings>
    <add key ="UserId" value ="myUserId"/>
     // several other <add key>s
</appSettings>

Usually I access the values using userId = ConfigurationManager.AppSettings["UserId"]

If I modify it using ConfigurationManager.AppSettings["UserId"]=something, the value is not saved to the file, and next time I load the application, it uses the old value.

How can I change the value of some app.config keys during runtime?

Louis Rhys
  • 34,517
  • 56
  • 153
  • 221

4 Answers4

82
System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

config.AppSettings.Settings["UserId"].Value = "myUserId";     
config.Save(ConfigurationSaveMode.Modified);

You can read about ConfigurationManager here

Rafal Spacjer
  • 4,838
  • 2
  • 26
  • 34
  • 12
    You should also have the following after that code: ConfigurationManager.RefreshSection("appSettings"); – SimonD Aug 11 '17 at 13:59
3

Modifying app.config File

using Microsoft.VisualBasic;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.Configuration;
using System.Xml;

public class AppConfigFileSettings
{


    public static void UpdateAppSettings(string KeyName, string KeyValue)
    {
        XmlDocument XmlDoc = new XmlDocument();

        XmlDoc.Load(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);

        foreach (XmlElement xElement in XmlDoc.DocumentElement) {
            if (xElement.Name == "appSettings") {

                foreach (XmlNode xNode in xElement.ChildNodes) {
                    if (xNode.Attributes[0].Value == KeyName) {
                        xNode.Attributes[1].Value = KeyValue;
                    }
                }
            }
        }
        XmlDoc.Save(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);
    }
}
Pranay Rana
  • 175,020
  • 35
  • 237
  • 263
  • 5
    There are special classes for working with app.config - you don't have to do it manualy – Rafal Spacjer Mar 29 '11 at 06:29
  • @Rafał Spacjer - i know that you can go for the special classes that already available in .net framwork but this just one solution that i applied in my project – Pranay Rana Mar 29 '11 at 06:32
  • 1
    but I don't think it's a good idea to invent wheel every time we need to do something. Needed functionality can be done in 3 lines of code instead of more then 10. – Rafal Spacjer Mar 29 '11 at 06:37
  • 1
    It may be desired not to re-write the entire file, just to change one element. And since the 3 lines of code do that, it surely winds up doing more actual 'work' in more lines, anyway. This ends up being a single line of code, where used. ;) – JoeBrockhaus Jun 21 '16 at 20:52
  • Isn't app.config only used at compile time? Hence the myExecutable.exe.config etc. – Austin Salgat Jun 13 '17 at 16:48
  • No. It's used at runtime as the final say in the application's configuration, aside from programmatic overrides. These values aren't compiled in, at all, for the standard app.config file placed alongside any standard .net program, unless you use the VS "Settings" interface to create it. And, even then, that just compiles in convenient accessors and defaults. The values in the file will still override those defaults, at runtime. This configuration scheme is also layered, from the local appname.exe.config all the way to machine level settings that your application can access. – dodexahedron Jan 28 '18 at 09:55
3

After changing the value, probably u will be not saving the Appconfig document.

// update    
  settings[-keyname-].Value = "newkeyvalue"; 
//save the file 
  config.Save(ConfigurationSaveMode.Modified);   
//relaod the section you modified 
  ConfigurationManager.RefreshSection(config.AppSettings.SectionInformation.Name); 
PawanS
  • 7,033
  • 14
  • 43
  • 71
2

On a side note.

If something in your app.config needs to change at runtime...its possible there's a better place to keep that variable.

App.config is used for constants. At worst case something with a one time initialization.

Whimsical
  • 5,985
  • 1
  • 31
  • 39
  • 1
    I agree, however there are cases where a connection string may inappropriately be entered in clear-text and you'd like to encrypt that on the fly IMO. – Adam Caviness Mar 27 '14 at 17:53
  • If you want to keep using the default configuration manager but be able to load external config files at startup, it becomes necessary. – Austin Salgat Jun 13 '17 at 16:49
  • Runtime at the start or end of your application is still runtime. – Victor Zakharov Jul 19 '17 at 11:42
  • For me it's a good idea to not use extra files merely for the benefit of simplicity. If there is already a .config file around and it can be used without conflicts, why have an extra file in a folder? – j riv Jun 14 '18 at 07:05
  • 1
    Outside of unit testing, I strongly agree. However, in the context of a unit test, it can be quite handy to be able to dynamically update config values to increase test coverage. – Sam May 02 '19 at 15:15
  • I some cases, such as referencing a webservice, VS auto dumps the imported service endpoints into the app config. Once deployed the endpoint host has to be dynamically updated to make the correct service calls. My point is that in some cases this is the only way. Although it is definitely not the best way. – Fütemire Dec 22 '21 at 23:29