Friday, September 4, 2009

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();

2 comments:

digital signatures said...

I am a newbie and after reading code think that its quite simple that web.config file can be changed by a c program but i cannot understand that in what situation this type of handling is required or i think this can be done if a user session is maintained

Anonymous said...

Could you help me what is the configfile path