5

I deployed a feature creating a new feature item in Visual Studio. I'm currently using SharePoint 2013.
I'm trying to activate this feature in C# by using the feature name. I need to activate it programmatically because I need to have it on more subsites.

var features = web.Features;

If I try to use the features.Add method I can only use a GUID but I need to activate the feature by using the name because the name is all I have.
How can I do it? There's a way?
I think I might use the features.FeatureDefinitions method in order to get all the features but when I use it I get an empty collection everytime.

1 Answer 1

2

Try below code:

You can use SPFarm.Local.FeatureDefinitions[featureName] for Web features

// Look for feature definition using feature name
SPFeatureDefinition featureDefinition = SPFarm.Local.FeatureDefinitions[featureName];

// Look for activated feature
SPFeature feature = web.Features.Cast().FirstOrDefault(f => f.DefinitionId == featureDefinition.Id);

// Deactivate feature if activated
if (feature != null)
{
    try
    {
        web.Features.Remove(feature.DefinitionId);
    }
    catch (Exception exc)
    { 
    }
}
else
{
    // Activate feature
    try
    {
        web.Features.Add(featureDefinition.Id);
    }
    catch (Exception exc)
    {     
    }
}
2
  • @Gautam Sheth : For "web.Features", not able to resolve 'web'. which dll should I include...?? I am using it for SharePoint online.
    – Koder101
    Oct 31, 2017 at 18:48
  • @Koder101 - can you ask a separate question, will be able to explain in more detail there ? the above code wont work in SharePoint online. Nov 1, 2017 at 5:30

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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