分享
 
 
 

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.

 
 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
2023年上半年GDP全球前十五强
 百态   2023-10-24
美众议院议长启动对拜登的弹劾调查
 百态   2023-09-13
上海、济南、武汉等多地出现不明坠落物
 探索   2023-09-06
印度或要将国名改为“巴拉特”
 百态   2023-09-06
男子为女友送行,买票不登机被捕
 百态   2023-08-20
手机地震预警功能怎么开?
 干货   2023-08-06
女子4年卖2套房花700多万做美容:不但没变美脸,面部还出现变形
 百态   2023-08-04
住户一楼被水淹 还冲来8头猪
 百态   2023-07-31
女子体内爬出大量瓜子状活虫
 百态   2023-07-25
地球连续35年收到神秘规律性信号,网友:不要回答!
 探索   2023-07-21
全球镓价格本周大涨27%
 探索   2023-07-09
钱都流向了那些不缺钱的人,苦都留给了能吃苦的人
 探索   2023-07-02
倩女手游刀客魅者强控制(强混乱强眩晕强睡眠)和对应控制抗性的关系
 百态   2020-08-20
美国5月9日最新疫情:美国确诊人数突破131万
 百态   2020-05-09
荷兰政府宣布将集体辞职
 干货   2020-04-30
倩女幽魂手游师徒任务情义春秋猜成语答案逍遥观:鹏程万里
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案神机营:射石饮羽
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案昆仑山:拔刀相助
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案天工阁:鬼斧神工
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案丝路古道:单枪匹马
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案镇郊荒野:与虎谋皮
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案镇郊荒野:李代桃僵
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案镇郊荒野:指鹿为马
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案金陵:小鸟依人
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案金陵:千金买邻
 干货   2019-11-12
 
推荐阅读
 
 
 
>>返回首頁<<
 
靜靜地坐在廢墟上,四周的荒凉一望無際,忽然覺得,淒涼也很美
© 2005- 王朝網路 版權所有