Search This Blog

Wednesday, March 21, 2012

SharePoint web.config modification programmatically using c#

Here is the sample code to customize the web.config file for the SharePoint site programmatically
spSite = new SPSite(http://intranet.demo.com);
SPWeb spWeb = spSite.OpenWeb();
SPWebService service = SPWebService.ContentService;
SPWebApplication webApp = new SPSite("http://intranet.demo.com").WebApplication;
Configuration config = WebConfigurationManager.OpenWebConfiguration("/", spSite.WebApplication.Name);
XmlDocument doc = new XmlDocument();
doc.Load(configFilePath);
AppSettingsSection appSettings = config.AppSettings;
if (appSettings.ElementInformation.IsPresent)
{
XmlNode nodekey = doc.SelectSingleNode("configuration/appSettings/add[@key='key']");
if(nodekey == null)
{
SPWebConfigModification myModification = new SPWebConfigModification();
myModification.Path = "configuration/appSettings";
myModification.Name ="add[@key='userName']";
myModification.Sequence = 0;
myModification.Owner = "User Name";
myModification.Type = SPWebConfigModification.SPWebConfigModificationType.EnsureChildNode;
myModification.Value =
";
service.WebConfigModifications.Add(myModification);
}
}
/*Call Update and ApplyWebConfigModifications to save changes*/
service.Update();
service.ApplyWebConfigModifications();
As you can see, it is pretty simple and if you want to apply to the site spWeb.Site.WebApplication.WebConfigModifications.Add(MyModification)
If you want to apply to the whole farm
webApp.Farm.Services.GetValue().ApplyWebConfigModifications();
wenApp.Update();

No comments:

Post a Comment