views:

71

answers:

3

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)configurationSectionGroup.Sections[...];

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

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

Only from an internal application.

abatishchev
+2  A: 

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

Rajesh Rolen- DotNet Developer
@: can you plez tell me why you have given me -1. because i have tested it and its working fine with app.config.
Rajesh Rolen- DotNet Developer
A: 

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.

ben f.