Click here to Skip to main content
11,717,620 members (81,241 online)
Click here to Skip to main content

Modifying Configuration Settings at Runtime

, 3 Jan 2006 128.3K 65
Rate this:
Please Sign up or sign in to vote.
This article will demonstrate how to add, delete, and update key value pairs in an App.config file.

Introduction

This article will demonstrate how to add, delete, and update key value pairs in an App.config file at runtime.

Background

Visual Studio .NET has hinted that more powerful support for modifying App.config files at runtime will come with the release of .NET 2.0. Since I didn't want to wait that long, I'm providing the following class containing four methods that will enable you to modify the App.config (or Web.config, with a few minor changes) at runtime. Some of you may have noticed that accessing the System.Configuration.ConfigurationSettings.AppSettings.Add("key","value") throws an exception (collection is read-only). To get around this, I've written the methods shown below, in the hopes that this will be useful if you have an application that requires users to add, edit, or delete database connection strings, or other such configuration data at runtime.

Using the code

I'm going to go ahead and tack a disclaimer on this article before we begin. Modifying a configuration file at runtime can cause some nasty, unexpected behavior inside your application if it's not managed properly. I'm only giving out the code that will show you how to do it-- please adhere to your own good judgment when determining what key value pairs you will be editing!

Adding New Key-Value Pairs

The following method demonstrates how to add a key and a value to your configuration. It loads the App.config as an XML document, adds the key name and value to the appSettings node, and saves the document in two places. It will use the helper method KeyExists to ensure the key doesn't already exist in the configuration.

// Adds a key and value to the App.config
public void AddKey(string strKey, string strValue)
{
    XmlNode appSettingsNode = 
      xmlDoc.SelectSingleNode("configuration/appSettings");
    try
    {
        if (KeyExists(strKey))
            throw new ArgumentException("Key name: <" + strKey + 
                      "> already exists in the configuration.");
        XmlNode newChild = appSettingsNode.FirstChild.Clone();
        newChild.Attributes["key"].Value = strKey;         
        newChild.Attributes["value"].Value = strValue;   
        appSettingsNode.AppendChild(newChild);
        //We have to save the configuration in two places, 
        //because while we have a root App.config,
        //we also have an ApplicationName.exe.config.
        xmlDoc.Save(AppDomain.CurrentDomain.BaseDirectory + 
                                     "..\\..\\App.config");
        xmlDoc.Save(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);
    }
    catch (Exception ex)
    {
        throw ex;
    }
}

Updating Key-Value Pairs

The following method updates an existing key value pair in the App.config. It will utilize the helper method KeyExists to ensure we have a key to update.

// Updates a key within the App.config
public void UpdateKey(string strKey, string newValue)
{
    if (!KeyExists(strKey))
        throw new ArgumentNullException("Key", "<" + strKey + 
              "> does not exist in the configuration. Update failed.");
    XmlNode appSettingsNode = 
       xmlDoc.SelectSingleNode("configuration/appSettings");
    // Attempt to locate the requested setting.
    foreach (XmlNode childNode in appSettingsNode)   
    {      
        if (childNode.Attributes["key"].Value == strKey)         
            childNode.Attributes["value"].Value = newValue;   
    }
    xmlDoc.Save(AppDomain.CurrentDomain.BaseDirectory + 
                                 "..\\..\\App.config");
    xmlDoc.Save(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);
}

Deleting Key-Value Pairs

The following method will delete an existing key value pair from the App.config. It will utilize the helper method KeyExists to ensure we have a key to delete.

// Deletes a key from the App.config
public void DeleteKey(string strKey)
{
    if (!KeyExists(strKey))
        throw new ArgumentNullException("Key", "<" + strKey + 
              "> does not exist in the configuration. Update failed.");
    XmlNode appSettingsNode = 
       xmlDoc.SelectSingleNode("configuration/appSettings");
    // Attempt to locate the requested setting.
    foreach (XmlNode childNode in appSettingsNode)   
    {      
        if (childNode.Attributes["key"].Value == strKey)   
            appSettingsNode.RemoveChild(childNode);
    }
    xmlDoc.Save(AppDomain.CurrentDomain.BaseDirectory + "..\\..\\App.config");
    xmlDoc.Save(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);
}

Helper Method

KeyExists is a simple helper method that returns a boolean value indicating whether or not the targeted key actually exists in the App.config. It is used in all three of the above methods.

// Determines if a key exists within the App.config
public bool KeyExists(string strKey)
{
    XmlNode appSettingsNode = 
      xmlDoc.SelectSingleNode("configuration/appSettings");
    // Attempt to locate the requested setting.
    foreach (XmlNode childNode in appSettingsNode)   
    {      
        if (childNode.Attributes["key"].Value == strKey)
            return true;
    }
    return false;
}

Points of Interest

That's the long and the short of it. I'm not going to include a project, since the methods are fairly straightforward. Common sense would dictate that our application will require read/write permissions on the App.config in order to save changes. Also of particular note is the behavior of the configuration file. Once our Forms application has loaded, the App.config has already loaded, so, if you're doing something like, say, loading databases from the configuration, you probably won't want to use the common System.Configuration.ConfigurationSettings.AppSettings["key"] syntax. You're better off looping through the App.config as an XML document, like so:

//This code will add a listviewitem 
//to a listview for each database entry 
//in the appSettings section of an App.config file.
private void loadFromConfig()
{
    this.lstDatabases.Items.Clear();
    XmlDocument xmlDoc = new XmlDocument();
    xmlDoc.Load(AppDomain.CurrentDomain.BaseDirectory + 
                                 "..\\..\\App.config");
    XmlNode appSettingsNode = 
      xmlDoc.SelectSingleNode("configuration/appSettings");
    foreach (XmlNode node in appSettingsNode.ChildNodes)
    {
        ListViewItem lvi = new ListViewItem();
        string connStr = node.Attributes["value"].Value.ToString();
        string keyName = node.Attributes["key"].Value.ToString();
        lvi.Text = keyName;
        lvi.SubItems.Add(connStr);
        this.lvDatabases.Items.Add(lvi);
    }
}

Happy coding!

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

Share

About the Author

UsualDosage
Architect
United States United States
I have been an ASP.NET/C# Programmer/Software Architect for about 10 years, specializing in web architecture, user interface, and user experience. I formerly wrote business applications for mortgage banking front-ends in C++ before switching to the .NET Framework many years ago, and I've never looked back. I'm an evangelist of HTML5 and web standards, and spend the majority of my time working on front end design, performance and scale.

My primary website is located at http://www.usualdosage.com

You may also be interested in...

Comments and Discussions

 
QuestionAwesome snippet Pin
Sreedevi Pidaparthi15-May-12 1:32
memberSreedevi Pidaparthi15-May-12 1:32 
GeneralMy vote of 2 Pin
vnenad24-Feb-09 8:45
membervnenad24-Feb-09 8:45 
GeneralModify connectionstrings and servicemodel in .config Pin
alhambra-eidos30-Sep-08 5:09
memberalhambra-eidos30-Sep-08 5:09 
GeneralQuestion on saving the app.config file... Pin
michaelloveusa5-Jun-08 12:34
membermichaelloveusa5-Jun-08 12:34 
GeneralThank you :) Pin
dariol16-Oct-07 22:05
memberdariol16-Oct-07 22:05 
GeneralCorrection: loading app.config at runtime if application is installed Pin
danel2655-Oct-07 3:38
memberdanel2655-Oct-07 3:38 
GeneralRe: Correction: loading app.config at runtime if application is installed Pin
UsualDosage5-Oct-07 9:17
memberUsualDosage5-Oct-07 9:17 
GeneralRe: Correction: loading app.config at runtime if application is installed Pin
danel2655-Oct-07 20:29
memberdanel2655-Oct-07 20:29 
GeneralRe: Correction: loading app.config at runtime if application is installed Pin
UsualDosage8-Oct-07 12:47
memberUsualDosage8-Oct-07 12:47 
GeneralRe: Correction: loading app.config at runtime if application is installed Pin
michaelloveusa5-Jun-08 12:37
membermichaelloveusa5-Jun-08 12:37 
GeneralRe: Correction: loading app.config at runtime if application is installed Pin
UsualDosage6-Jun-08 14:07
memberUsualDosage6-Jun-08 14:07 
GeneralRe: Correction: loading app.config at runtime if application is installed Pin
Ed Gadziemski29-Jul-08 15:53
memberEd Gadziemski29-Jul-08 15:53 
GeneralAnother Approach Pin
jothar7331-Jul-07 8:40
memberjothar7331-Jul-07 8:40 
GeneralRe: Another Approach Pin
UsualDosage31-Jul-07 14:31
memberUsualDosage31-Jul-07 14:31 
Generalgreat article ... i hope this helps Pin
aguriuc31-Mar-07 0:58
memberaguriuc31-Mar-07 0:58 
GeneralRe: great article ... i hope this helps Pin
UsualDosage31-Jul-07 14:30
memberUsualDosage31-Jul-07 14:30 
GeneralRe: great article ... i hope this helps Pin
Jacquers15-Jul-09 21:42
memberJacquers15-Jul-09 21:42 
GeneralPermission hurdle while updating config file Pin
Rama Krishna Pillai14-Feb-07 22:52
memberRama Krishna Pillai14-Feb-07 22:52 
GeneralRe: Permission hurdle while updating config file Pin
UsualDosage15-Feb-07 3:14
memberUsualDosage15-Feb-07 3:14 
GeneralRe: Permission hurdle while updating config file Pin
ramdil17-Jun-07 23:37
memberramdil17-Jun-07 23:37 
GeneralUpdate App.config at runtime Pin
Member #370134225-Jan-07 2:51
memberMember #370134225-Jan-07 2:51 
GeneralRe: Update App.config at runtime Pin
UsualDosage25-Jan-07 4:15
memberUsualDosage25-Jan-07 4:15 
GeneralThanks Pin
masant113-Nov-06 22:58
membermasant113-Nov-06 22:58 
GeneralRe: Thanks Pin
UsualDosage14-Nov-06 7:11
memberUsualDosage14-Nov-06 7:11 
GeneralRe: Thanks Pin
Laura Monge18-Aug-08 8:01
memberLaura Monge18-Aug-08 8:01 
Questionkeep the orginal format Pin
isponder18-Sep-06 15:28
memberisponder18-Sep-06 15:28 
AnswerRe: keep the orginal format Pin
UsualDosage19-Sep-06 3:54
memberUsualDosage19-Sep-06 3:54 
Generalsave configuration, [modified] Pin
peyotest16-Aug-06 16:00
memberpeyotest16-Aug-06 16:00 
GeneralRe: save configuration, Pin
UsualDosage17-Aug-06 8:36
memberUsualDosage17-Aug-06 8:36 
GeneralComment Problem Pin
kyawsoe5-Apr-06 18:27
memberkyawsoe5-Apr-06 18:27 
GeneralRe: Comment Problem Pin
UsualDosage17-Aug-06 8:41
memberUsualDosage17-Aug-06 8:41 
GeneralRe: Comment Problem Pin
Kyaw Soe Khaing17-Aug-06 16:05
memberKyaw Soe Khaing17-Aug-06 16:05 
GeneralProblem for Refresh Pin
kyawsoe21-Feb-06 0:48
memberkyawsoe21-Feb-06 0:48 
GeneralRe: Problem for Refresh Pin
UsualDosage21-Feb-06 4:14
memberUsualDosage21-Feb-06 4:14 
GeneralI did something on this matter... Pin
Alexandru Stanciu10-Jan-06 4:40
memberAlexandru Stanciu10-Jan-06 4:40 
GeneralRe: I did something on this matter... Pin
UsualDosage10-Jan-06 9:36
memberUsualDosage10-Jan-06 9:36 
GeneralClickety ;-) Pin
Uwe Keim18-Apr-06 0:04
sitebuilderUwe Keim18-Apr-06 0:04 
GeneralRe: Clickety ;-) Pin
Alexandru Stanciu18-Apr-06 0:20
memberAlexandru Stanciu18-Apr-06 0:20 
GeneralRe: Clickety ;-) Pin
Uwe Keim18-Apr-06 0:28
sitebuilderUwe Keim18-Apr-06 0:28 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.150901.1 | Last Updated 3 Jan 2006
Article Copyright 2006 by UsualDosage
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid