SharePoint Config

Using SharePoint SPWebConfigModification to manage changes to the web.config


The following tips relate to working with the SharePoint SPWebConfigModification API in order to manage changes to the web.config. Note it’s not recommended that you modify the web.config directly as this may have side effects with the running of your SharePoint instance, and changes may be lost when installing updates or service packs.

Avoiding Duplicates

When working with the SPWebConfigModification API, the name property should be set to an xPath expression that identifies the configuration change being made. This should be an expression relative to the Path property. This prevents duplicate changes being made in the web.config. If an arbitrary name is used instead, then the system will not throw an error but may lead to duplicate entries.

SPWebService service = SPWebService.ContentService;

SPWebApplication webApp = properties.Feature.Parent as SPWebApplication;

myModification.Path = "configuration/system.web/httpModules";

myModification.Name = "add[@name='myModule']";

myModification.Sequence = 0;
myModification.Owner = this.GetType().FullName;
myModification.Type = SPWebConfigModification.SPWebConfigModificationType.EnsureChildNode;
myModification.Value = "<add name='myModule' type='myModule, myAssembly' />";


Removing Entries

To ensure your entries can be removed via code (such on feature deactivate), it’s a good idea to set the owner of the SPWebConfigModification instance as in the example above. It’s then possible to loop through the config settings and remove the entries that were previously set by the same codebase

SPWebApplication webApp = properties.Feature.Parent as SPWebApplication;
Collection<spwebconfigmodification>modsCollection = webApp.WebConfigModifications;
int count = modsCollection.Count;
for (int i = count-1; c >= 0; i--)
 SPWebConfigModification mod = modsCollection[i];
 if (mod.Owner == this.GetType().FullName)