SharePoint Blogs / SharePoint University
SharePoint Blogs and SharePoint University - all in one place!
Need SharePoint Training? Attend a SharePoint Bootcamp!

Please delete cookies related to sharepointblogs.com and sharepointu.com to resolve login issues!

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 ...


Posted 09-04-2007 4:22 PM by nsevens

Comments

paul wrote re: Activate features through code
on 10-25-2007 12:37 PM

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

nsevens wrote re: Activate features through code
on 11-23-2007 6:58 AM

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 ...

Shishir wrote re: Activate features through code
on 02-07-2008 3:39 PM

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

Michael Leppan wrote re: Activate features through code
on 08-14-2008 8:17 AM

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

Frode Magnussen wrote re: Activate features through code
on 08-19-2008 2:29 PM

Great tip Nick. Thanks :)

nsevens wrote re: Activate features through code
on 08-21-2008 1:59 AM

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 ...

.neting in the free world wrote Egzamin 70-541 - WSS 3.0 Application Development
on 10-28-2008 3:51 PM

Wstęp No cóż, muszę powiedzieć że było warto :) Nawet nie z samego powodu zdania egzaminu, ale z tego

mark wrote re: Activate features through code
on 12-21-2008 3:09 PM

Thanks Nick, Just what i was after.

Sudip wrote re: Activate features through code
on 04-10-2009 3:49 AM

Hi

Do you know how to activate farm features through code?

nsevens wrote re: Activate features through code
on 04-21-2009 1:45 AM

Probably something like SPFarm.Local.FeatureDefinitions.Add(.....)

Sanjay wrote re: Activate features through code
on 05-11-2009 8:13 AM

How do I check if the feature id already activated or not?

Add a Comment

(required)  
(optional)
(required)  
Remember Me?
Need SharePoint Training? Attend a SharePoint Bootcamp!
Posts (c) their respective authors. Everything else (c) 2009 SharePoint Experts, Inc.