How to get all folders in SPList and then check "Contribute" permission for current user

I have a sharepoint list:

List ---------Folder 1 -----------------Item 1 -----------------Item 2 ---------Folder 2 -----------------Item 1 -----------------Item 2 ---------Folder 3 -----------------Item 1 -----------------Item 2 
  • How can I get all the folders in a List ?

  • After that, if the current user has Contribute permission on Folder 1 , Folder 2 , Folder 3 ?

+6
source share
3 answers

To get a list of list folders, you can use the Folders property of the SPList object:

 private SPFolderCollection GetListFolders(SPList list) { return list.Folders; // you can also do: // return list.Folders.Cast<SPFolder>().ToList(); // to return a List<SPFolder> instead of a SPFolderCollection } 

To check if a given user has Contribute permissions in a folder, you should get the SPListItem associated with the SPFolder, tag for the RoleAssignment this user and check his RoleDefinitionBindings to determine the role of the Contribute

 private bool HasContributePermissionOnFolder(SPFolder folder, SPPrincipal user) { var contributePermission = folder.ParentWeb.RoleDefinitions["Contribute"]; var roleAssignementsOfUser = folder.Item.RoleAssignments.Cast<SPRoleAssignment>() .Where(ra => ra.Member == user); var hasContributePermission = roleAssignementsOfUser .Where(ra => ra.RoleDefinitionBindings.Contains(contributePermission)).Count() > 0; return hasContributePermission; } 

Usage example

 //remember to add using System.Linq; for the above code to work //SPList list = <your list>; //SPWeb web = <your web>; var folders = GetAllFoldersOfList(list); foreach (SPFolder folder in folders) { if (HasContributePermissionOnFolder(folder, spWeb.CurrentUser)) { // do stuff } 
+3
source
 private IEnumerable<SPFolder> GetListFolders(SPList list) { return list.Folders.OfType<SPListItem>().Select(item => item.Folder); } 
+1
source

Verifying user rights by verifying their membership in role definitions is a bit risky. Who will say that the role definition will not be renamed or that the basic permissions included in the role definition will not be changed.

If the goal is primarily to check the current user rights on the protected object, then I think the best way is to simply call one of the overloaded DoUserHavePermissions methods for SPSecurableObject (SPListItem, SPList, SPWeb or SPSite) with the required mask resolution.

0
source

Source: https://habr.com/ru/post/894802/


All Articles