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.

European Sharepoint 2013 Hosting

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

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 .

Don’t forget, this code will not work on a site that has inherited permissions.