13

How can I create a new SharePoint group by code?

10
SPWeb root = site.RootWeb;
SPGroup group = null;

// Check if the group exists
try
{                                     
    group = root.SiteGroups["The Group Name"];
}
catch { }

// If it doesn't, add it
if (group == null)
{
    root.SiteGroups.Add("The Group Name", member, root.Author, "Your Group Description");
    group = root.SiteGroups["The Group Name"];

    // Add the group's permissions
    SPRoleDefinition roleDefinition = root.RoleDefinitions.GetByType(SPRoleType.Contributor);
    SPRoleAssignment roleAssignment = new SPRoleAssignment(group);
    roleAssignment.RoleDefinitionBindings.Add(roleDefinition);
    root.RoleAssignments.Add(roleAssignment);
    root.Update();
}
| improve this answer | |
  • Is there compulsory to update the root (root.update()) in the end ? – Dipen Shah Dec 30 '15 at 9:58
  • @DipenShah Try it without and see if it persists :) – RJ Cuthbertson Dec 30 '15 at 21:34
4

Creating the group is simple just call SPGroupCollection.Add

using (SPWeb oWebsiteRoot = SPContext.Current.Site.RootWeb)
{
    SPGroupCollection collGroups = oWebsiteRoot.SiteGroups;
    SPUser oUser = oWebsiteRoot.Users["User_Name"];
    SPMember oMember = oWebsiteRoot.Users["User_Name"];

    collGroups.Add("Group_Name", oMember, oUser, "Description");
}

Then you need may need to add users/groups and permissions depending on your needs

| improve this answer | |
  • 8
    The code for creating the group is perfect. But I don't think you should dispose the RootWeb object created from SPContext.Current.Site. Details here: msdn.microsoft.com/en-us/library/office/… – Vardhaman Deshpande May 16 '14 at 15:20
  • RJ Cuthbertson's answer is closer to how I'd want things to work - after creating a group you also want to associate it to a site, and this is done by using the SPRoleDefinition/SPRoleAssignment combo. – Vlad May 10 '15 at 11:47
0

One alternative to @RJ Cuthbertson 's answer to avoid empty try/catch block when testing whether group with that name has already been created:

SPGroup group = w.SiteGroups.Cast<SPGroup>().SingleOrDefault(g => g.Name == "The Group Name");

// If it doesn't, add it
if (group == null)
{
    root.SiteGroups.Add("The Group Name", member, root.Author, "Your Group Description");
    group = root.SiteGroups["The Group Name"];

    // Add the group's permissions
    SPRoleDefinition roleDefinition = root.RoleDefinitions.GetByType(SPRoleType.Contributor);
    SPRoleAssignment roleAssignment = new SPRoleAssignment(group);
    roleAssignment.RoleDefinitionBindings.Add(roleDefinition);
    root.RoleAssignments.Add(roleAssignment);
    root.Update();
}
| improve this answer | |

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.