All about modifying web.config in Sharepoint environment.
Following are the different approaches that i have figured out that can possibly be used to modify web.config:
1. Rich API SPWebConfigModification
2. Declarative approach by having the changes in webconfig.*.xml
3. using ASP.net configuration
4. Modifying it as just another xml file
Sharepoint api is compiled so well that the changes that are written to web.config
can be easilty removed as well. A code sample to add the WCF/webservice entry using this API can be found here.
When we are so used to do everything as a xml file. Ofcourse its the easiest way of
implementing things in sharepoint and so in this case.
In this approach the modifications to the web.config can be defined in a XML file
that will named as webconfig.*.xml,placed in 12\config folder.
When a new webapplication is getting created sharepoint looks up for the files with pattern webconfig.*.xml
under 12/config and merges those changes with the web.config
Please note that this works only for new webapps and it impacts all webapps but not a specific
To have these new changes to be included in web.config for existing webapp the following stsadm command
can be run:
stsadm -o copyappbincontent
3..Net Configuration API
All the elements/nodes and attributes of web.config are implemented as various classes and properties.
This will be a large chunk of code once you are used to SPWebConfigModification API.
Below is the code sample using Configuration class that will modify a entry in appSettings section.
public void Modify(string key, string value)
Configuration configuration = WebConfigurationManager.OpenWebConfiguration("~");
AppSettingsSection appSettingsSection = (AppSettingsSection)configuration.GetSection("appSettings");
if (appSettingsSection != null)
appSettingsSection.Settings[key].Value = value;
4.As an xml file.
Best way to parse the xml files is to use XMLReader/XMLTextReader,XMLWriter/XMLTextWriter,XPathNavigator
but it would be a pain to write the changes as each node and attribute.
Again it depends on the requirement what to add/modify?
XmlDocument document = new XmlDocument();
document.Load(file);// file - web.config opened on FileStream
XmlNode node = document.SelectSingleNode("/configuration");
node.InnerXml = node.InnerXml + serviceModelChange;
more details can be found at http://www.west-wind.com/Weblog/posts/2423.aspx
I summarize that SPWebConfigModification is the best/safe way of modifying web.config programmatically.