SharePoint: SPWebConfigModification Note

I’ve just been working on automating some changes to web.config using SPWebConfigModification. I have done this a while ago, but forgot the difference between two parameters (it is important that these are set correctly – if name is not set correctly, adding web.config nodes may work, but remove wont work):

  • XPath – the path to the parent node where your web.config node will be added to.
  • Name – the xpath used to identify your web.config node, from the parent web.config node specified path the above Xpath.

Example code:

using (SPSite site = new SPSite(url))
{
    // Get webapp and ensure that previous mods are cleared
    SPWebApplication webApp = site.WebApplication;
    webApp.WebConfigModifications.Clear();

    string xPath = “configuration/system.web/securityPolicy”;
    string name = “trustLevel[@name=\”Custom_TrustLevel\”]”;

    // Note – you should create multiple mods before ApplyWebConfigModifications, as
    // opposed to calling for each change
    SPWebConfigModification mod = new SPWebConfigModification(name, xPath);
    mod.Value = “<trustLevel name=\”Custom_TrustLevel\” policyFile=\”C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\12\config\Custom_TrustLevel.config\” />”;
    mod.Type = SPWebConfigModification.SPWebConfigModificationType.EnsureChildNode;
    webApp.WebConfigModifications.Add(mod);

    // Apply the modifications
    webApp.Farm.Services.GetValue<SPWebService>().ApplyWebConfigModifications();
    webApp.Farm.Update();
    webApp.Update();
}

You May Also Like

About the Author: rnowik

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.