Directly editing the web.config file is not recommended. Doing so could result in an invalid file, and the application could stop working. Even worse, it could become insecure in some way without noticing. To avoid this, the process of Web Part deployment and registering the assembly or its parts as safe should be closely followed, as shown in the next code snippet.
public override void FeatureActivated(SPFeatureReceiverProperties properties)
// A reference to the features site collection
SPSite site = null;
// Get a reference to the site collection of the feature
if (properties.Feature.Parent is SPWeb)
site = ((SPWeb)properties.Feature.Parent).Site;
else if (properties.Feature.Parent is SPSite)
site = properties.Feature.Parent as SPSite;
if (site != null)
SPWebApplication webApp = site.WebApplication;
// Create a modification
SPWebConfigModification mod = new SPWebConfigModification(
// Add the modification to the collection of modifications
// Apply the modification
This code shows how to modify web.config using the appropriate classes called from a feature event receiver. If the Web Part is part of a feature and the feature is activated, the event is fired and the code executed. The code first checks the parent object the receiver refers to (i.e., the context object it’s installed in). From that object, the SPWebApplication object is pulled to get the web.config file that contains the site’s configuration. An XPath expression that contains the complete token and the path where it has to be added is used to get the configuration. A farm service is used finally to apply the modifications.