how to access SharePoint web config Programmatically

In SharePoint 2010, you can easily access SharePoint's Web.Config file using SPWebConfigModification class of the Microsoft.SharePoint.Administration namespace.
It can be used in the situations where you might need to write an assembly to SafeControls element in your web config file using object model or may be something else.Well, the cool thing is these modifications are written to the web.config files on every front-end web server when the SPWebService.ApplyWebConfigModifications method is called.

Below is an example shows how to use the SPWebConfigModification class to register a custom assembly.

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 = "";

/*Call Update and ApplyWebConfigModifications to save changes*/

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.


Post a Comment


This is a personal weblog. The opinions expressed here represent my own and not those of my employer or anyone else. Should you have any questions or concerns please e-mail me at .

Copyright (c) 2010 @ All rights are reserved.Do Not Copy.

@ Learning