Tuesday, May 17, 2011

Programmatically set permissions to a folder in a SharePoint list

This method can be used to bind permission to a folder in a SharePoint list

 /// <summary>
/// Method to set the permission at folder level for the newly created site groups
/// </summary>
/// <param name="web">The current web instance</param>
/// <param name="groupName">Name of the Site group that is added to the folder</param>
/// <param name="listName">Name of the list</param>
/// <param name="folderName">Name of the folder in the list</param>
/// <param name="role">Role/permission level set to the group to access folder for the site group users</param>

 private void SetRoleDefinitionBinding(SPWeb web,string groupName, string listName, string folderName, string role)
        {
            try
            {
                SPRoleAssignment roleAssignment = new SPRoleAssignment((SPPrincipal)web.SiteGroups[groupName]);
                SPList list = web.Lists[listName];
                SPQuery query = new SPQuery();
                    query.Query = "<Where><Eq><FieldRef Name='Title'/><Value Type='Text'>" + folderName + "</Value></Eq></Where>";
                //Retrieve the items based on Query
                SPListItemCollection items = list.GetItems(query);
               
                //Get the name and Url for the folder
                foreach (SPListItem item in items)
                {
                    SPFolder folder = web.GetFolder(item.Url);
                    folder.Item.BreakRoleInheritance(true);
                    roleAssignment.RoleDefinitionBindings.Add(web.RoleDefinitions[role]);
                    folder.Item.RoleAssignments.Add(roleAssignment);
                    web.Update();
                }
      
            }
            catch (Exception ex)
            {
              
                //Error handling
            }
        }

No comments:

Post a Comment