saving web.config file

  • Thread starter Thread starter Blue Man
  • Start date Start date
B

Blue Man

Anybody has idea how to save value in web.config file during runtime?
ConfigurationSettings.AppSettings.Add("test","test value");

won't work, it will cause and error : the file is read only during rumtime.
 
That is correct and for good reason. When you make a change to the
machine.config/web.config files, it causes your application to restart. Not
too gracfully, I might add. There are a couple of work-arounds though.

A. Use a separate config file aside from web.config to hold runtime values
that might change.
B. Here is some code that will work, but USE IT AT YOUR OWN RISK. I have not
tested it, nor would I on a running asp.net application as it would cause
the application to restart as soon as it can.

using System.IO;
using System.Xml;

private void AddWebConfigValue(string name, string val)
{
try
{
//first we need to grab the web.config file.
string webconfig = Server.MapPath("./web.config");
if(File.GetAttributes(webconfig) == FileAttributes.ReadOnly)
{
File.SetAttributes(webconfig, FileAttributes.Normal);
}

XmlDocument doc = new XmlDocument();
doc.load(webconfig);
XmlNode node =
doc.DocumentElement.SelectSingleNode("configuration/appSettings");
if(null != node)
{
XmlNode ne = doc.CreateNode(XmlNodeType.Element,"add","");
ne.Attributes["key"] = name;
ne.Attributes["value"] = val;
node.AppendChild(ne);
}

doc.Save(webconfig);
File.SetAttributes(webconfig, FileAttributes.ReadOnly);
}
catch(Exception ex)
{
//aw crap... ;)
}
}

HTH,
Bill P.
 
Back
Top