Search code examples
sharepointsharepoint-2010web-configwebconfigurationmanager

How to add section to web config programmatic in SharePoint


I have lot of custom entries to be made in a web config in SharePoint. Is there a way we can do it programatically. such as i have this to add under

 <PageParserPath>
<PageParserPath VirtualPath="/*" CompilationMode="Always" AllowServerSideScript="true"      IncludeSubFolders="true" />

also i have a complete new section to be added called

<connectionstring>
entries here
</connectionstring>

how can i do it programtically any ideas please


Solution

  • Use SPWebConfigModification:

    http://spmatt.wordpress.com/2013/05/22/using-spwebconfigmodification-to-update-the-web-config-in-sharepoint-2013/

    In your case you would have something along these lines:

            var httpRuntimeModification = new SPWebConfigModification();
            httpRuntimeModification.Path = "configuration/PageParserPath";
            httpRuntimeModification.Name = "myModification";
            httpRuntimeModification.Sequence = 0;
            httpRuntimeModification.Owner = "MyAppName";
            httpRuntimeModification.Type = SPWebConfigModification.SPWebConfigModificationType.EnsureChildNodes;
            httpRuntimeModification.Value = "<PageParserPath VirtualPath='/*' CompilationMode='Always' AllowServerSideScript='true'      IncludeSubFolders='true' />";
            webApp.WebConfigModifications.Add(httpRuntimeModification);
    

    You probably have to tweak the Xpath as I am not sure where this element lives in the web.config

    You should use this in a feature receiver where you can get the reference to your webapplication and you should always remove them on feature deactivation