in

SharePoint Blogs

The Best Place for SharePoint-related Blogs

Nick's SharePoint Blog

Activate features through code

For a recent project I did, I had to activate a feature programatically.

I needed some research to achieve this, so I thought I'd just put it in a post. It's only a few lines of code, so nothing hard to do here ...

Basically, what it does is update the FeatureCollection object of a given Site or Site Collection. Adding a feature to this collection automatically activates it.

! Do make sure the feature is already installed in the farm/site/web/... when trying to activate it.

SPWeb web = new SPSite("http://yourserver.com").OpenWeb();

SPFeatureCollection featureCollect = web.Features;

featureCollect.Add(new Guid("xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"), true); //True to force activation

That's all it takes :) 
Hope it helps someone ...

Published Sep 04 2007, 04:22 PM by nsevens
Filed under: , ,

Comments

 

paul said:

you can also use web.features.add(guid) is a bit less code

October 25, 2007 12:37 PM
 

nsevens said:

It think that's quite obvious, as we just use the SPFeatureCollection assigned to web.Features :|

It's just to make it a little more clear what object it used ...

November 23, 2007 6:58 AM
 

Shishir said:

Thanks...u saved me a day's time !

February 7, 2008 3:39 PM
 

Michael Leppan said:

Please explain how do you get this class to run from feature.xml?

August 14, 2008 8:17 AM
 

Frode Magnussen said:

Great tip Nick. Thanks :)

August 19, 2008 2:29 PM
 

nsevens said:

Michael,

I don't think it's adviced to try to run this class from the feature file itself, since the code would only be run at the moment you actually activate the feature ...

August 21, 2008 1:59 AM

Leave a Comment

(required )  
(optional )
(required )  
Add

Need SharePoint Training? Attend a SharePoint Bootcamp!

Posts (c) their respective authors. Everything else (c) 2007 SharePoint Experts