How to do Enable-SPFeature equievalent in object model. I want to enable some features (lists) in my publishing site in event receiver. For example:

Enable-SPFeature announcementslist -url URL_OF_SITE

How can i activate announcementslist by code in event receiver?


You can use SPWeb or SPSite to activate features on subsite or a certain site collection respectively. Here is an example of SPWeb.

           SPWeb oWebSite = SPContext.Current.Web;
           feature = oWebSite.Features[new GUID("94C94CA6-B32F-4da9-A9E3-1F3D343D7ECB")];
           if (feature == null)//if feature is not activated  
           //Activating a feature using Object Model    
           oWebSite.Features.Add(new GUID("94C94CA6-B32F-4da9-A9E3-1F3D343D7ECB");
         catch (Exception ex)

  • oWeb.Features.Add is equal to Enable-SPFeature ? And what to do for activating the feature in site collection scope. – ozdogan Nov 9 '12 at 9:11
  • 1
    use SPSite.Features.Add to add/activate a Site Collection scope feature, call the Add method and pass it the GUID of the feature. Be warned that it will throw an InvalidOperationException if the feature is already activated. – Falak Mahmood Nov 9 '12 at 9:16
  • Very thanks Falak.. What is the best practice to handle exception. Or can we firstly look if the feature is already activated, before running the code? – ozdogan Nov 9 '12 at 9:20
  • 1
    I have updated the code with general exception handling. – Falak Mahmood Nov 9 '12 at 9:31

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.