Prasad Bolla's SharePoint Blog

Click Here to go through the Interesting posts within my Blog.

Click Here to go through the new posts in my blog.

Friday, December 02, 2011

How to add a SPGroup to a Site Collection- SharePoint


Groups cannot directly be added to a site-they must be added to the site collection.
If you try to add a group to the site’s Groups collection, you get an exception stating, “You cannot add a group directly to the Groups collection. You can add a group to the SiteGroups collection.”

This situation occurs because the SPGroup is always created at the Site Collection level and assigned to the site. The following code is valid and adds the LitwareSecurityGroup to the site collection groups.

// Adds a new group to the site collection groups:
site.SiteGroups.Add("LitwareSecurityGroup", site.CurrentUser,site.CurrentUser, "A group to manage Litware Security");

However, this still does not associate the group with our site, nor would it be useful within the site without any permissions. To add the group to the site, create a new SPRoleAssignment by associating an SPRoleDefinition with the SPGroup, and then add that role assignment to the site, as in the following code sample:


SPGroup secGroup = site.SiteGroups["LitwareSecurityGroup"];
SPRoleAssignment roleAssignment = new SPRoleAssignment(secGroup);
SPRoleDefinition roleDefinition = site.RoleDefinitions["Full Control"];
roleAssignment.RoleDefinitionBindings.Add(roleDefinition);
site.RoleAssignments.Add(roleAssignment);

No comments:

Post a Comment