Set permissions on SharePoint list and items programmatically
02/27/2011 Leave a comment
This is a short guide on how to set permissions on a SharePoint list/item using server-side object model.
- Get the principal object (SPPrincipal) to which you want to grant permission to. It by sharepoint user or group.
- Get the list
SPList list = web.GetListFromUrl(web.Url + “/Lists/ListName/Forms/AllItems.aspx“);
- Break role inheritance for the list
list.BreakRoleInheritance(false);
or pass ‘true’ if you want to copy the current role assignments when breaking the role inheritance.
- Create new instance of SPRoleAssignment
SPRoleAssignment roleAssignment = new SPRoleAssignment(principal);
- Create new instance of SPRoleDefinition
SPRoleDefinition roleDefinition = new SPRoleDefinition();
- Set the SPRoleType you want to the role definition.
Example for read permissions:roleDefinition = web.RoleDefinitions.GetByType(SPRoleType.Reader);
- Create new instance of SPRoleDefinitionBindingsCollection and add the role definition created above
SPRoleDefinitionBindingCollection roleDefinitionBindingCollection = new SPRoleDefinitionBindingCollection();
- Import the role definition binding collection to the role assignment
roleAssignment.ImportRoleDefinitionBindings(roleDefinitionBindingCollection);
- Add the role assignment to the list’s role assignments collection
list.RoleAssignments.Add(roleAssignment);
Here is the complete code for setting read permissions for a principal:
SPRoleAssignment roleAssignment = new SPRoleAssignment(principal); SPRoleDefinition roleDefinition = new SPRoleDefinition(); roleDefinition = web.RoleDefinitions.GetByType(SPRoleType.Reader); SPRoleDefinitionBindingCollection roleDefinitionBindingCollection = new SPRoleDefinitionBindingCollection(); roleDefinitionBindingCollection.Add(roleDefinition); roleAssignment.ImportRoleDefinitionBindings(roleDefinitionBindingCollection); web.AllowUnsafeUpdates = true; list.RoleAssignments.Add(roleAssignment); web.AllowUnsafeUpdates = false;
The same logic is valid for setting item’s permissions by just replacing SPList with SPListItem in the code:
SPRoleAssignment roleAssignment = new SPRoleAssignment(principal); SPRoleDefinition roleDefinition = new SPRoleDefinition(); roleDefinition = web.RoleDefinitions.GetByType(SPRoleType.Reader); SPRoleDefinitionBindingCollection roleDefinitionBindingCollection = new SPRoleDefinitionBindingCollection(); roleDefinitionBindingCollection.Add(roleDefinition); roleAssignment.ImportRoleDefinitionBindings(roleDefinitionBindingCollection); web.AllowUnsafeUpdates = true; item.RoleAssignments.Add(roleAssignment); web.AllowUnsafeUpdates = false;