Modify SharePoint Web.config When Feature Is Activated

This article demonstrates how to modify the SharePoint web.config file when a feature is activated.

Reference
Microsoft.SharePoint.dll

Code
public static SPWebConfigModification AddAppSettings(Guid ownerId) {    SPWebConfigModification configMod = new SPWebConfigModification; configMod = new SPWebConfigModification; configMod.Name = @"appSettings"; configMod.Path = "configuration"; configMod.Sequence = 0; configMod.Owner = ownerId.ToString; configMod.Type = SPWebConfigModification.SPWebConfigModificationType.EnsureSection; configMod.Value = ""; return configMod; } // The following block makes use of the helper method above. public override void FeatureActivated(SPFeatureReceiverProperties properties) {    SPSite site = properties.Feature.Parent as SPSite; using (SPWeb web = site.OpenWeb) {        SPWebApplication webApplication = site.WebApplication; webApplication.WebConfigModifications.Clear; webApplication.WebConfigModifications.Add(AddAppSettings(properties.Feature.DefinitionId)); webApplication.Update(true); webApplication.Farm.Services.GetValue.ApplyWebConfigModifications; } } // Remove web.config changes when feature is deactivated public override void FeatureDeactivating(SPFeatureReceiverProperties properties) {       SPSite site = properties.Feature.Parent as SPSite; SPWebApplication webApplication = site.WebApplication; Collection oCollection = webApplication.WebConfigModifications; int iStartCount = oCollection.Count; bool bRemoved = false; for (int c = iStartCount - 1; c >= 0; c--) {          // Removes modifications made by this feature SPWebConfigModification oModification = oCollection[c]; if (oModification.Owner == properties.Feature.DefinitionId.ToString) {             webApplication.WebConfigModifications.Remove(oModification); bRemoved = true; }       }        if (bRemoved) {          webApplication.Update(true); webApplication.Farm.Services.GetValue.ApplyWebConfigModifications; } }