Return to Snippet

Revision: 21683
at December 18, 2009 10:46 by blackf0rk


Initial Code
//get a handle on our sites and web(s)
SPSite Site = new SPSite("<sharepoint url>");
SPWeb Web = Site.OpenWeb();

//get a handle on our users (we need an owner and a member to add a group). Se my snippet on adding users to SharePoint if you don't have the user in SharePoint that you'd like to add.
SPUserCollection users = Web.AllUsers;
SPUser owner = users["DOMAIN\username"];
SPMember member = users["DOMAIN\username"];

//get a handle on all our sites' groups
SPGroupCollection groups = Web.SiteGroups;

//add the new group
groups.Add("<group name>", member, owner, "<group description>");

//add the role definition and assignment
SPGroup <group name> = groups["<group name>"];
//You can change "Full Control" to Read, Design, or Contribute:
SPRoleDefinition role = Web.RoleDefinitions["Full Control"];
SPRoleAssignment roleAssignment = new SPRoleAssignment(<group name>);
roleAssignment.RoleDefinitionBindings.Add(role);
Web.RoleAssignments.Add(roleAssignment);
Web.Update();

Initial URL


Initial Description
An important thing to keep in mind about adding groups is that you add groups to site collections and not webs. To do this, we access the SiteGroups collection rather than the Groups collection.

In order to assign permissions, each group you add needs a role definition (i.e. Read, Contribute, Design, or Full Control). It's best practice to assign role definitions to a group and assign users to the group, rather than assign definitions to individual users.

Initial Title
Add a new group to SharePoint Site Collection; Add Role Definition and Assignment

Initial Tags
sharepoint

Initial Language
C#