How to add specific SharePoint Group to List permission

mkacar picture mkacar · Aug 1, 2012 · Viewed 18.7k times · Source
using (SPSite site = (SPSite)properties.Feature.Parent)
{
   using (SPWeb web = site.OpenWeb())
   {
        if (web != null)
        {
              web.AllowUnsafeUpdates = true;
              SPList list = web.Lists["Alert Status v1.0"];

              //Creates a new role assignment for a group
              SPGroup myGroup = web.SiteGroups["IKM Manager"];
              SPRoleAssignmentCollection roleAssignments = web.RoleAssignments;

              // SPRoleAssignment accepts a SPPrincipal which can be a SPUser or SPGroup
              SPRoleAssignment roleAssignment = new SPRoleAssignment(myGroup);

              //Add the new role assignment to the collection of role assignments for the site.
              roleAssignments.Add(roleAssignment);

              // Stop inheriting permissions
              list.BreakRoleInheritance(true);
              list.RoleAssignments.Add(roleAssignment);
              list.Update();

I have error on RoleAssignments.Add(roleAssignment) like "Cannot add a role assignment with empty role definition binding collection". I want to stop inheriting permissions and add specific group to List permissions. Can you help me? please..

Thanks

Answer

Rahil picture Rahil · Aug 3, 2012

This should work.

list.BreakRoleInheritance(true);
SPGroup groupAdmin = web.SiteGroups["IKM Manager"];
SPRoleAssignment roleAssignmentAdmin = new SPRoleAssignment((SPPrincipal)groupAdmin);
SPRoleDefinition roleAdmin = web.RoleDefinitions.GetByType(SPRoleType.Administrator);
roleAssignmentAdmin.RoleDefinitionBindings.Add(roleAdmin);
list.RoleAssignments.Add(roleAssignmentAdmin);
list.Update();