How to: Assign a Permission Level to a SharePoint Group
Posted
Wednesday, April 2, 2008 10:11 AM
by
CoreyRoth
Earlier this week, I covered how to add a SharePoint Group to a Site Collection, but I did not cover how, you set the permission level of that group. It's one thing to get the group added, but of course the people in that group are going to need some sort of permission to the site or site collection. The first thing we need to do is translate one of the terms that we see in the UI to what they are called in the API. The first thing is Permission Level. This defines the set of permissions that can be assigned to a user or group on the site (i.e.: Read, Contribute, Full Control, etc.). It represents a set of permssions, not just a single permission. You can create your own permission levels as well, which I will cover in a future post. In the API, this is called a RoleDefinition. You can view what RoleDefinitions have been defined for your site by going to Site Settings -> Advanced Permissions -> Settings -> Permission Levels.
To assign a permission level, we have to make use of the SPRoleAssignment class. You get a SPRoleAssignment class by passing it a user or group in its constructor. This class has a collection called RoleDefinitionBindings to which you add the RoleDefinitions. Once you assign the permission levels (or RoleDefinitions) to this RoleAssignment class, you update the site. Here is what the code looks like.
SPRoleAssignment roleAssignment = new SPRoleAssignment(currentSiteCollection.RootWeb.SiteGroups["My Site Group"]);
roleAssignment.RoleDefinitionBindings
.Add(currentSiteCollection.RootWeb.RoleDefinitions["Read"]);
currentSiteCollection.RootWeb.RoleAssignments.Add(roleAssignment);
currentSiteCollection.RootWeb.Update();
In this case, I am assigning the read permission level to the group. The reason I cover this today is that the way you assign the permission level to a group is not entirely obvious at first. You would think you would just get a reference to the group and add the permissions to a collection.