Removing Configuration Settings

The IConfigManager interface defines a single method named RemoveKeyFromPropertyBag that you can use to remove configuration data from any level of the SharePoint hierarchy. The following code shows how to use the RemoveKeyFromPropertyBag method to remove a configuration setting.

using Microsoft.Practices.ServiceLocation;            
using Microsoft.Practices.SharePoint.Common.Configuration;
using Microsoft.Practices.SharePoint.Common.ServiceLocation;
using Microsoft.SharePoint; //for the SPContext object

IServiceLocator serviceLocator = SharePointServiceLocator.GetCurrent();
IConfigManager configManager = serviceLocator.GetInstance<IConfigManager>();

// Remove configuration data at the SPWeb level
IPropertyBag bag = configManager.GetPropertyBag(ConfigLevel.CurrentSPWeb);

// Remove configuration data at the SPSite level.
bag = configManager.GetPropertyBag(ConfigLevel.CurrentSPSite);

// Remove configuration data at the SPWebApplication level.
bag = configManager.GetPropertyBag(ConfigLevel.CurrentSPWebApplication);

// Remove configuration data at the SPFarm level.
// Note that you cannot do this from a content Web application.
bag = configManager.GetPropertyBag(ConfigLevel.CurrentSPFarm);

The first argument to the RemoveKeyFromPropertyBag method is the key of the configuration setting to be deleted. This should be a string that was previously used in a corresponding invocation of the SetInPropertyBag method. The RemoveKeyFromPropertyBag method does not fail if the key cannot be found, so this method can be safely called to ensure that the key is removed.

The second argument to the RemoveKeyFromPropertyBag is an object of type IPropertyBag that represents the property bag in which the configuration data is stored. You can use the GetPropertyBag method to retrieve the property bag instance from the ConfigManager class.

If the SharePoint context is unavailable, you must provide the ConfigManager class with an SPWeb object as the starting point for the current SharePoint hierarchy (SPWeb, SPSite, SPWebApplication, and SPFarm) before you delete any settings. To do this, call the ConfigManager.SetWeb method. The following example shows how you could use this approach to remove an application setting at the SPSite level.

using(SPSite remoteSite = new SPSite (""))
  IPropertyBag bag = configManager.GetPropertyBag(ConfigLevel.CurrentSPSite);

The permissions for removing items from the property bags are the same as the permissions for update and create defined in the previous section.