开发者

web.config: Changing an application setting with C#

How can I change an application setting within a web.copnfig programmatically with C# (from another application, which configures the web-application)? The following code snipped doesn't work, because AppSettings[...] is readonly!

configuration = WebConfigurationManager.OpenWebConfiguration(...);

ConfigurationSectionGroup configurationSectionGroup = (ConfigurationSectionGroup)configuration.GetSectionGroup("applicationSettings");

ConfigurationSection configurationSection = (ConfigurationSection)co开发者_如何学JAVAnfigurationSectionGroup.Sections[...];

configurationSection.CurrentConfiguration.AppSettings[...].value = value


you can change app.config. i have done that by loading it as an XML document and changed its nodes. i think same can be done for webюconfig.

this is example how to read web.config using XML, but use can do some changes in it to use it for writing: http://dotnetacademy.blogspot.com/2010/10/read-config-file-using-xml-reader.html

XmlDocument xmlDoc = new XmlDocument();     
xmlDoc.Load(Server.MapPath("~/") + "app.config");     
XmlNode node = xmlDoc.SelectSingleNode("Root/Node/Element");  
node.Attributes[0].Value = newValue;     
xmlDoc.Save(xmlFile);

below link is providing a good example how to change value of xml node: http://www.fryan0911.com/2009/10/change-xml-file-node-value-using-c.html


You can't change App.config or Web.config from the host application, i.e. own settings from itself.

Only from an internal application.


Since no one has said this yet, please, please never change the web.config settings programatically in a ASP.NET application. The second that change is made (no matter how it is accomplished) will cause the Application Pool to immediately restart, causing your caches to flush, your user sessions to drop, poor performance, and all sorts of other bad things. If the setting needs to be able to be changed at runtime, find another place to store it. There is a reason why the Microsoft engineers made the AppSettings class readonly. Also, if you were in a multi-server environment, you would only be changing the web.config for 1 of the servers, leaving your setting in different states on your different servers.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜