You can add and remove configuration values in the Web.config file for a Web application programmatically, by using the SPWebConfigModification class. The following Microsoft C# code examples demonstrate how to add and remove configuration values programmatically
Adding Configuration Values
SPWebApplication spweb = SPWebApplication.Lookup(new Uri("")); SPWebConfigModification myModification = new SPWebConfigModification(); myModification.Path = "configuration/SharePoint/SafeControls"; myModification.Name = "SafeControl [@Assembly='MyCustomAssembly'] [@Namespace='MyCustomNamespace'][@TypeName='*'][@Safe='True']"; myModification.Sequence = 0; myModification.Owner = '""; myModification.Type = SPWebConfigModification.SPWebConfigModificationType.EnsureChildNode; myModification.Value = "<SafeControl Assembly='MyCustomAssembly' Namespace='MyCustomNamespace' TypeName='*' Safe='True' />"; spweb.WebConfigModifications.Add(myModification); spweb.Update(); spweb.Farm.Services.GetValue<SPWebService>().ApplyWebConfigModifications();
Removing Configuration Values
SPWebConfigModification configModFound1 = null; SPWebApplication spweb1 = SPWebApplication.Lookup(new Uri("")); Collection<SPWebConfigModification> modsCollection1 = spweb1.WebConfigModifications; int modsCount1 = modsCollection1.Count; for (int i = modsCount1 - 1; i > -1; i--) { if (modsCollection1[i].Owner == "OwnerName") { configModFound1 = modsCollection1[i]; modsCollection1.Remove(configModFound1); spweb1.Update(); spweb1.Farm.Services.GetValue<SPWebService>().ApplyWebConfigModifications();
See Also
Reference
Microsoft.SharePoint.Administration.SPWebConfigModificationOther Resources
Working with Web.config FilesI'm the contributor for this article. I would like to make some changes in the code.
Adding Configuration Values:
There is typo in the code. Line No:6
myModification.Owner = " "; //Name of the owner
Removing Configuration Values:
The code is meant to delete values in the config file based on certain condition. Here the condition is based on the owner. It could be any property of SPWebConfigModification depending on the requirements. There is a typo here. Here is the complete code.
SPWebConfigModification configModFound1 = null;
SPWebApplication spweb1 = SPWebApplication.Lookup(new Uri(""));
Collection<SPWebConfigModification> modsCollection1 = spweb1.WebConfigModifications;
int modsCount1 = modsCollection1.Count;
for (int i = modsCount1 - 1; i > -1; i--)
{
if (modsCollection1[i].Owner == "OwnerName")
{
configModFound1 = modsCollection1[i];
modsCollection1.Remove(configModFound1);
spweb1.Update();
spweb1.Farm.Services.GetValue<SPWebService>().ApplyWebConfigModifications();
}
}
Please update the article. Thanks.