How To: Programmatically Add and Remove Web.config values

This content is outdated and is no longer being maintained. It is provided as a courtesy for individuals who are still using these technologies. This page may contain URLs that were valid when originally published, but now link to sites or pages that no longer exist.

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.SPWebConfigModification

Concepts

Working with Web.config Files