Runtime Web.config / App.config Editing
By Peter A. Bromberg, Ph.D.
Printer - Friendly Version
Peter Bromberg

Web.config configuration files and app.config project item files, which get converted to "ExecutableName.exe.config" at build time, both support the convenient appSettings section with its own read method in the System.Configuration.ConfigurationSettngs class. The appSettings section stores element name / value pairs in the format:

<add key="elementName" value="elementValue" />

You can store as many of these <add> elements as you want, read them out at runtime, and use the values in the application. If you have an item that contains multiple values and you would like to keep them together, you can store them as a single string, delimited with a pipe | or other symbol, read them out at runtime, and call the String.Split() method to parse them into a useable string array.

I often read out my appSetting values into a NameValueCollection at runtime, which provides one-shot acess to the entire collection in memory:

NameValueCollection mySettings = System.Configuration.ConfigurationSettings.AppSettings;
string connStr = mySettings["connString"];

But what about being able to change, add, and save appSettings items while that app is running in response to user input or other actions, instead of just reading them out? Nada, Zippo, Efes!  You have to open the config file manually and add them by "hand". Well that kinda stinks, don't you think? So here's my take on a convenient little class that allows you to either modify, add or delete any appSettings element, in either your Executable, Console or ASP.NET web application at runtime, on the fly. Bear in mind of course, that if you modify a web.config on a running ASP.NET app, the ASP.NET worker process will recycle. Users currently using your app aren't exactly guaranteed to have a fun experience when this happens...



using System;
using System.Xml;  
using System.Configuration;
using System.Collections;
using System.Reflection;  
using System.Diagnostics ;

public enum   ConfigFileType
{
 WebConfig ,
 AppConfig
}

public class AppConfig : System.Configuration.AppSettingsReader
{ 
 public string  docName = String.Empty;
 private  XmlNode node=null;

 private int _configType;
public int ConfigType { get { return _configType; } set { _configType=value; } } public bool SetValue(string key, string value) { XmlDocument cfgDoc = new XmlDocument(); loadConfigDoc(cfgDoc); // retrieve the appSettings node node = cfgDoc.SelectSingleNode("//appSettings"); if( node == null ) { throw new System.InvalidOperationException( "appSettings section not found"); } try { // XPath select setting "add" element that contains this key XmlElement addElem= (XmlElement)node.SelectSingleNode("//add[@key='" +key +"']") ; if (addElem!=null) { addElem.SetAttribute("value",value); } // not found, so we need to add the element, key and value else { XmlElement entry = cfgDoc.CreateElement("add"); entry.SetAttribute("key",key); entry.SetAttribute("value",value); node.AppendChild(entry); } //save it saveConfigDoc(cfgDoc,docName); return true; } catch { return false; } } private void saveConfigDoc(XmlDocument cfgDoc,string cfgDocPath) { try { XmlTextWriter writer = new XmlTextWriter( cfgDocPath , null ); writer.Formatting = Formatting.Indented; cfgDoc.WriteTo( writer ); writer.Flush(); writer.Close(); return; } catch { throw; } } public bool removeElement ( string elementKey) { try { XmlDocument cfgDoc = new XmlDocument(); loadConfigDoc(cfgDoc); // retrieve the appSettings node node = cfgDoc.SelectSingleNode("//appSettings"); if( node == null ) { throw new System.InvalidOperationException( "appSettings section not found"); } // XPath select setting "add" element that contains this key to remove node.RemoveChild( node.SelectSingleNode("//add[@key='" +elementKey +"']") ); saveConfigDoc(cfgDoc,docName); return true; } catch { return false; } } private XmlDocument loadConfigDoc( XmlDocument cfgDoc ) { // load the config file if( Convert.ToInt32(ConfigType)==Convert.ToInt32(ConfigFileType.AppConfig)) { docName= ((Assembly.GetEntryAssembly()).GetName()).Name; docName += ".exe.config"; } else { docName=System.Web.HttpContext.Current.Server.MapPath("web.config"); } cfgDoc.Load( docName ); return cfgDoc; } }


I'm sure the above can be improved, but it works just fine for me. Notice that if you attempt to modify an element that doesn't exist, we assume that we need to create it for you. In the downloadable solution below you'll find sample projects for a Web application and a Winforms executable, both of which contain sample code to use this class. Note that there are three subfolders under the solution when you unzip this, and the one named "appConfigWeb" needs to be made an IIS virtual directory / application. Enjoy!

Download the code that accompanies this article

 


Peter Bromberg is a C# MVP, MCP, and .NET consultant who has worked in the banking and financial industry for 20 years. He has architected and developed web - based corporate distributed application solutions since 1995, and focuses exclusively on the .NET Platform.