Take the 2-minute tour ×
SharePoint Stack Exchange is a question and answer site for SharePoint enthusiasts. It's 100% free, no registration required.

How can I create a new SharePoint group by code?

share|improve this question
add comment

2 Answers 2

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();
}
share|improve this answer
add comment

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

share|improve this answer
2  
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 at 15:20
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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