Oct 18, 2007

Runtime Web.config / App.config Editing




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:

You can store as many of these 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...

Original Source: http://www.eggheadcafe.com/articles/20030907.asp
By Peter A. Bromberg, Ph.D.

No comments:

Post a Comment