Articles about European Sharepoint Hosting Service
SharePoint 2013 Hosting UK – HostForLIFE.eu :: How to Add SharePoint group to a site ?
One day, I need to Add SharePoint group to a site. The thing is that you have to create the group on the site collection, and then you assign it to the required site. To make use of the group you also need to grant some rights to it (“Full Control”, “Contribute” etc). Assigning the group to the site and granting the rights are perfomed using the SPRoleAssignment and SPRoleDefinition classes, respectively.
Because a group has to be created on the site collection, you must add it to the site’s SiteGroups collection. Attempting to adding it directly to the Groups collection will result in an exception. The only way to get the group into the Groups collection is by assigning it to the parent site. The code snippet below demonstrates how to create the tester’s group to an SharePoint site
1 |
using (SPSite site = new SPSite("your_site_col/subsite")) { using(SPWeb web = site.OpenWeb()) { web.SiteGroups.Add("Testers", web.CurrentUser, web.CurrentUser, "Group for Testers"); } |
At this point the group has been created on the site collection. To add the group to your site, you create an SPRoleAssignment object by associating the group in the constructor. Then, create an SPRoleDefinition object with the required permission level (taken from the site’s RoleDefinition collection), and then add it to the SPRoleAssignment object’s RoleDefinitionBindings collection. Now, add the SPRoleAssignment object to the site’s RoleAssignment collection .
1 2 3 4 5 |
SPGroup group = web.SiteGroups["Testers"]; SPRoleAssignment roleAssignment = new SPRoleAssignment(group); SPRoleDefinition roleDefinition = web.RoleDefinitions["Contribute"]; roleAssignment.RoleDefinitionBindings.Add(roleDefinition); web.RoleAssignments.Add(roleAssignment); |
Don’t forget, this code will not work on a site that has inherited permissions.
Print article | This entry was posted by Peter on October 2, 2014 at 7:59 am, and is filed under European SharePoint 2013 Hosting. Follow any responses to this post through RSS 2.0. You can leave a response or trackback from your own site. |