Click here to Skip to main content
Licence 
First Posted 3 Jan 2006
Views 87,055
Bookmarked 57 times

Modifying Configuration Settings at Runtime

By UsualDosage | 3 Jan 2006
This article will demonstrate how to add, delete, and update key value pairs in an App.config file.
3 votes, 20.0%
1
2 votes, 13.3%
2
1 vote, 6.7%
3

4
9 votes, 60.0%
5
3.95/5 - 15 votes
μ 3.95, σa 3.08 [?]

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

About the Author

UsualDosage

Web Developer

United States United States

Member
I have been an ASP.NET/C# Programmer for about 7 years, specializing in business applications for financial institutions. I formerly wrote business applications for mortgage banking front-ends in C++ before switching to the .NET Framework, which I program in almost exclusively, now, except for my occasional contract dalliances in PHP and MySQL, which I really like. I especially enjoy graphic design, and web work.

In my spare time I run the local internet radio portal Jaxrockradio.com.

I have long moonlighted as an ANSI C programmer for several online MUDs (still a hobby of mine), and probably will continue to as long as they let me.

You can view my blog by visiting http://www.usualdosage.com.

My site design portfolio is located at http://design.usualdosage.com


Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board. (secure sign-in)
 
Search this forum  
 FAQ
    Noise  Layout  Per page   
  Refresh
GeneralMy vote of 2 Pinmembervnenad9:45 24 Feb '09  
GeneralModify connectionstrings and servicemodel in .config Pinmemberalhambra-eidos6:09 30 Sep '08  
GeneralQuestion on saving the app.config file... Pinmembermichaelloveusa13:34 5 Jun '08  
GeneralThank you :) Pinmemberdariol23:05 16 Oct '07  
GeneralCorrection: loading app.config at runtime if application is installed Pinmemberdanel2654:38 5 Oct '07  
GeneralRe: Correction: loading app.config at runtime if application is installed PinmemberUsualDosage10:17 5 Oct '07  
GeneralRe: Correction: loading app.config at runtime if application is installed Pinmemberdanel26521:29 5 Oct '07  
GeneralRe: Correction: loading app.config at runtime if application is installed PinmemberUsualDosage13:47 8 Oct '07  
GeneralRe: Correction: loading app.config at runtime if application is installed Pinmembermichaelloveusa13:37 5 Jun '08  
GeneralRe: Correction: loading app.config at runtime if application is installed PinmemberUsualDosage15:07 6 Jun '08  
GeneralRe: Correction: loading app.config at runtime if application is installed PinmemberEd Gadziemski16:53 29 Jul '08  
GeneralAnother Approach Pinmemberjothar739:40 31 Jul '07  
GeneralRe: Another Approach PinmemberUsualDosage15:31 31 Jul '07  
Generalgreat article ... i hope this helps Pinmemberaguriuc1:58 31 Mar '07  
GeneralRe: great article ... i hope this helps PinmemberUsualDosage15:30 31 Jul '07  
GeneralRe: great article ... i hope this helps PinmemberJacquers22:42 15 Jul '09  
GeneralPermission hurdle while updating config file PinmemberRama Krishna Pillai23:52 14 Feb '07  
GeneralRe: Permission hurdle while updating config file PinmemberUsualDosage4:14 15 Feb '07  
GeneralRe: Permission hurdle while updating config file Pinmemberramdil0:37 18 Jun '07  
GeneralUpdate App.config at runtime PinmemberMember #37013423:51 25 Jan '07  
GeneralRe: Update App.config at runtime PinmemberUsualDosage5:15 25 Jan '07  
GeneralThanks Pinmembermasant123:58 13 Nov '06  
GeneralRe: Thanks PinmemberUsualDosage8:11 14 Nov '06  
GeneralRe: Thanks PinmemberLaura Monge9:01 18 Aug '08  
Questionkeep the orginal format Pinmemberisponder16:28 18 Sep '06  

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.

Permalink | Advertise | Privacy | Mobile
Web04 | 2.5.120210.1 | Last Updated 3 Jan 2006
Article Copyright 2006 by UsualDosage
Everything else Copyright © CodeProject, 1999-2012
Terms of Use
Layout: fixed | fluid