Runtime Web.config / App.config Editing

王朝other·作者佚名  2006-01-09
窄屏简体版  字體: |||超大  

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.ConmfigurationSettings.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...

New Articles & Tips

SQL Server Reporting Services - Lessons Learned

Dr. Dotnetsky's Cool .NET Tips and Tricks # 18

.NET Compact Framework Save Signature To File

Compressed Ink for Tablet PC and Windows XP

WebService Enabling SQL Server 2005 Methods

HOWTO: Register an Assembly in the GA

.NET Framework 1.1 SP1 - Issues

Circular References / Memory Leaks /other baddies

Rsources Section Now Open for Testing!

.NET Compact Framework App.Config Workaround

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 began programming at Merrill Lynch, developing computerized trading programs, later becoming a Development Manager and Senior Programmer at medical and financial services firms. In 2001, he was lead developer on a jointly-funded project with Microsoft to convert COM banking services middleware to the new .NET platform. The technology tested at Microsoft Testing Lab at 10 times faster than any previous implementation. Peter has architected numerous enterprise - level business solutions with .NET, and is the co-founder of eggheadcafe.com. His samples at gotdotnet.com have been downloaded over 26,000 times. He is a Microsoft MVP, and is currently a Senior Developer at AspSoft, based in Orlando.

Do you have a question or comment about this article? Have a programming problem you need to solve? Post it at eggheadcafe.com forums and receive immediate email notification of responses.

 
 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
 
 
© 2005- 王朝網路 版權所有 導航