I am creating a site definition by code and I have a requirement to create the security groups in the site definition.

How can I create the user security groups in the site definition using the Visual Studio code?

Please guide.

1 Answer 1


You can staple a feature to do this programmatically.

Add a Feature and associate it an event receiver. Then, in the public override void FeatureActivated(SPFeatureReceiverProperties properties) method add the following code:

public override void FeatureActivated(SPFeatureReceiverProperties properties)
    SPWeb web = (SPWeb)properties.Feature.Parent;
    web.SiteGroups.Add("NameOfTheGroup", web.CurrentUser,
                    web.CurrentUser, "DescriptionOfTheGroup");
   //If you want to add users to the group
   web.SiteGroups[NameOfTheGroup].AddUser("UserLoginName", string.Empty, "UserLoginName", string.Empty);

In your onet.xml to staple the feature you have to reference in like this:

  <Configuration ID="0" Name="Your-Name-Space" MasterUrl="_catalogs/masterpage/Your-Master(If-you-use-it).master">
      <Feature ID="Add-Here-The-ID-of-Your-Feature" />
  • Thanks a lot. Can you also provide me with the URL so that I can refer the complete post and I do not miss out on anything. Oct 14, 2013 at 8:59
  • this solution is not from any post. It is based on my own experience deploying sites, collaborating in projects and so on. If you have any doubt feel free to ask
    – Alvmad
    Oct 14, 2013 at 9:16
  • Right, I can understand this. Can you please send me a zipped demo solution if possible. it would be a great help to me. Oct 14, 2013 at 10:01
  • I will try to do in my non working hours because I am at work now
    – Alvmad
    Oct 14, 2013 at 10:10
  • This code works fine but when the feature is activated I get "The specified name is already in use." error. Please help how can I solve it. Oct 14, 2013 at 11:13

Your Answer

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

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