2LeggedSpider

Edit Web.config at run-time

Posted in ASP.NET, C# by Sumit Thomas on February 21, 2006

[tweetmeme style=”compact”]I had an argument with one of my friends recently on his statement that Web.config cannot be edited at run-time. My counter statement was if it is a XML file and if you have write permission on it then you can do it. Here is the code to do the same…

public class ConfigManager
{
 //The file path of Web.config
 static string configFilePath =
 HttpContext.Current.Server.MapPath("~/web.config");
  
 /// Returns the Web.config as XmlDocument
 private static XmlDocument GetWebConfig()
 {
 XmlDocument xmlDoc = new XmlDocument();
 xmlDoc.Load( configFilePath );
 return xmlDoc;
 }

 /// Checks for the appSettings node in Web.config
 /// Updates the value for the given key if the key
 /// already exists or creates a new node for the
 /// given key and value combination if it is not present
 public static void CreateAppSetting( string key, string val )
 {
 XmlDocument xmlDoc = GetWebConfig();
 XmlNode xmlNode = xmlDoc.SelectSingleNode("//appSettings");
   
 if( xmlNode == null )
 {
  throw new Exception("appSettings node not found!");
 }

 string nodeFormat = string.Format("//add[@key='{0}']", key) );

 XmlElement xmlElement =
( (XmlElement) xmlNode.SelectSingleNode( nodeFormat );
 try
 {   
  if( xmlElement != null )
  {
   xmlElement.SetAttribute( "value", val );
  }
  else
  {
   xmlElement = xmlDoc.CreateElement( "add" );
   xmlElement.SetAttribute( "key", key );
   xmlElement.SetAttribute( "value", val );
   xmlNode.AppendChild( xmlElement );
  }
  SaveWebConfig( xmlDoc );
 }
 catch( Exception ex )
 {
  throw new Exception( ex.Message );
 }

 }

 /// Saves the changes to the Web.config file
 private static void SaveWebConfig( XmlDocument xmlDoc )
 {
  try
  {
  XmlTextWriter writer =
 new XmlTextWriter( configFilePath, null );
  writer.Formatting = Formatting.Indented;
  xmlDoc.WriteTo( writer );
  writer.Flush();
  writer.Close();
  }
  catch( Exception ex )
  {
  throw new Exception( ex.Message );
  }
 }
}//end of class

The application should have required permissions on Web.config to edit it, otherwise the code will throw an access denied error.

Technorati: , ,
Tagged with: ,