SharePoint features can exist at several different scopes, including Web, Site, and Web Application. Each of these can be activated and deactivated programmatically, but they have to be handled slightly differently.
This can be extremely useful for automated deployment tools, or any number of other purposes.
Given a WebApplication scoped feature, you’ll need an SPWebApplication object (which you can get from the property on your SPSite object if needed):
For example, if you wanted a method which could activate a WebApplication scoped feature, an optionally deactivate and reactivate (useful after upgrading the feature during a deployment):
<span class="kwrd">private</span> <span class="kwrd">void</span> ActivateWebApplicationFeature(SPWebApplication WebApplication, Guid FeatureGuid, <span class="kwrd">bool</span> Reactivate)
<span class="kwrd">if</span> (Reactivate)
<span class="rem">//Attempt to deactivate feature. Will fail if already deactivate.</span>
WebApplication.Features.Remove(FeatureGuid, <span class="kwrd">true</span>);
<span class="rem">//Was not activated, or could not be deactivated.</span>
<span class="rem">//Now activate</span>
For a feature scoped at the Site level, you simply leverage the SPSite object
And for the Web scoped features, of course, just use the SPWeb
The boolean on the remove indicates whether to force deactivation. Note that if the feature ID can not be found, permissions are not available, or it is already in the requested state, you will get a failure – So be sure to wrap your code with the appropriate error handling.