How to: Add and Remove Web.config Settings Programmatically

Switch View :
ScriptFree
How to: Add and Remove Web.config Settings Programmatically

Updated: July 2010

In Microsoft SharePoint Foundation, one way to modify web.config settings is to use the SPWebConfigModification class of the Microsoft.SharePoint.Administration namespace, which allows you to dynamically register entities. These modifications are persisted in the configuration database where they function as a kind of virtual web.config that effectively serves as the final layer of the .config file stack for the SharePoint Foundation web application. The changes become effective when the SPWebService.ApplyWebConfigModifications method is called.

TipTip

Sometimes these changes are also written to the physical web.config file, but SharePoint Foundation is not consistent in writing modifications to the physical file, so that file will not always reflect every SPWebConfigModification object that has been applied. When troubleshooting web.config modifications, examine the SPWebApplication.WebConfigModifications and SPWebService.WebConfigModifications properties as well as the physical file.

NoteNote

Code that calls ApplyWebConfigModifications works only if it runs in the user context of an administrator on the front-end web server.

NoteNote

For information about a second way of extending web.config files, see How to: Create a Supplemental .config File.

Example: Adding a Setting

The following example shows how to use the SPWebConfigModification class to register a custom assembly.

Visual Basic
Dim service As SPWebService = SPWebService.ContentService

Dim myModification As New SPWebConfigModification()
myModification.Path = "configuration/SharePoint/SafeControls"
myModification.Name = "SafeControl[@Assembly='MyCustomAssembly'][@Namespace='MyCustomNamespace'][@TypeName='*'][@Safe='True']"
myModification.Sequence = 0
myModification.Owner = "User Name"
myModification.Type = SPWebConfigModification.SPWebConfigModificationType.EnsureChildNode
myModification.Value = "<SafeControl Assembly='MyCustomAssembly' Namespace='MyCustomNamespace' TypeName='*' Safe='True' />"
service.WebConfigModifications.Add(myModification)

'Call Update and ApplyWebConfigModifications to save changes
service.Update()
service.ApplyWebConfigModifications()
C#
SPWebService service = SPWebService.ContentService;

SPWebConfigModification myModification = new SPWebConfigModification();
myModification.Path = "configuration/SharePoint/SafeControls";
myModification.Name = "SafeControl[@Assembly='MyCustomAssembly'][@Namespace='MyCustomNamespace'][@TypeName='*'][@Safe='True']";
myModification.Sequence = 0;
myModification.Owner = "User Name";
myModification.Type = SPWebConfigModification.SPWebConfigModificationType.EnsureChildNode;
myModification.Value = "<SafeControl Assembly='MyCustomAssembly' Namespace='MyCustomNamespace' TypeName='*' Safe='True' />";
service.WebConfigModifications.Add(myModification);
 
/*Call Update and ApplyWebConfigModifications to save changes*/ 
service.Update();
service.ApplyWebConfigModifications();

In the example, the Name property contains an XPath statement that uniquely identifies the node, which ensures that duplicates of the node are not added to the file.

Calling the ApplyWebConfigModifications method schedules a timer job to deploy the changes throughout the server farm. To apply a web.config modification to a specific Web application, add the modification to the collection of web.config modifications for the Web application (WebConfigModifications). For example, you can use oWebSite.Site.WebApplication.WebConfigModifications.Add(MyModification) to add a web.config modification to the parent Web application of a specific Web site. You must still call ApplyWebConfigModifications even if you add a web.config modification to a single Web application.

Removing Configuration Settings

The code to remove a configuration setting is similar, except that your modification is to remove a configuration setting. The following example shows how to remove a configuration setting. Notice that your code must still call ApplyWebConfigModifications

C#

SPWebConfigModification configModFound = null;
SPWebApplication webApplication = SPWebApplication.Lookup(new Uri("http://localhost/"));
Collection<SPWebConfigModification> modsCollection = webApplication.WebConfigModifications;

// Find the most recent modification of a specified owner
int modsCount1 = modsCollection.Count;
for (int i = modsCount1 - 1; i > -1; i--)
{
    if (modsCollection[i].Owner == "User Name")
    {
        configModFound = modsCollection[i];
    }
}

// Remove it and save the change to the configuration database  
modsCollection.Remove(configModFound);
webApplication.Update();

// Reapply all the configuration modifications
webApplication.Farm.Services.GetValue<SPWebService>().ApplyWebConfigModifications();

See Also

Tasks

Concepts

Change History

Date

Description

Reason

July 2010

Clarified effect of ApplyWebConfigModifications method on web.config files.

Content update

May 2010

Initial publication

Community Content

Reza Alirezaei
Limitations
Read about the limitations here : http://blogs.devhorizon.com/reza/?p=459

Pedro Cristo da Fonseca
Remove Web.config Setting not working
Having trouble on removing Web.config settings programmatically I tried this code (using SPWebService and SPWebApplication) hoping it would work but although the add works, the remove doesn´t seem to work.

I'm using the Add on a feature Activated method and the remove on a feature deactivated and the feature has WebApplication Scope.

I've tried the mentioned script but the result stayed the same.

Is there some necessary setting that I'm not aware of?

Moez T
Removal Notice
When the scripts run we can not compare with the Owner, because modification and the modofication removal wont be done by the same person.
I also recommend the use of SPWebService.WebConfigModifications instead of those in the SPWebApplication.

Regards

software-smith
Change in SP2010 requires PowerShell script before writing to web.config
Before changing the Web.config programmatically you will have to run a PowerShell script. See http://software-smith.blogspot.com/2011/04/writing-programmatically-to-webconfig.html. This is a change in SP2010 from SP2007. Hope this helps. Glen (Software) Smith MCM

Jim.B
STS web.config file
Apparently you can't use this class for modifying the web.config file in the 14/WebServices/SecurityToken directory. Other forum posts say to resort to manual XML file manipulation through code or using supplemental web.config files like here:
http://msdn.microsoft.com/en-us/library/ms460914.aspx

Unfortunately, I don't know if/how this works with the STS .config file.

Rickee
Cannot remove configuration setting

When I run the sample code for removing an entry, the modsCollection.Count is always 0...anyone know why?

MS: Because the webApplication.WebConfigModifications

from which you are trying to remove a modification is a different collection from the service.WebConfigModifications to which you added a modification in the preceding sample.


Rickee
re: Cannot remove configuration setting
The configuration modification is added through the SPWebService.ContentService and the removal is for the localhost WebApplication.
Think that's the error.


MS: Not an error. In addition to illustrating adding and removing, the two examples also are intended to illustrate that both SPWebService and SPWebApplication have a WebConfigModifications property.