How to grant user permission to certain folders us

2020-03-07 07:40发布

So far I am able to grant user certain permission with the following code:

    ClientContext context = new ClientContext("http://myRealURL");
    Principal user = context.Web.EnsureUser(@"myLoginAccout");

    RoleDefinition readDef = context.Web.RoleDefinitions.GetByName("Read");
    RoleDefinitionBindingCollection roleDefCollection = new RoleDefinitionBindingCollection(context);
    roleDefCollection.Add(readDef);
    RoleAssignment newRoleAssignment = context.Web.RoleAssignments.Add(user, roleDefCollection);

    context.ExecuteQuery(); 

The code above works fine, now my task is to add the user permission only to certain folders with C# code. For example, under Libraries, I have a library called JZhu, and inside JZhu, I have two folders folder1 and folder2. Is it possible to change the access permission on these two folders with Client Object Model?

enter image description here

enter image description here

1条回答
戒情不戒烟
2楼-- · 2020-03-07 08:16

The following example demonstrates how to customize access to folder via CSOM. There are two steps:

  1. assign unique permissions for a Folder since by default folder inherits permissions from the parent object (List)
  2. grant user permissions to a folder

Example:

Principal user = ctx.Web.EnsureUser(accountName);
var folder = ctx.Web.GetFolderByServerRelativeUrl(folderUrl);
var roleDefinition = ctx.Site.RootWeb.RoleDefinitions.GetByType(RoleType.Reader);  //get Reader role
var roleBindings = new RoleDefinitionBindingCollection(ctx) { roleDefinition };
folder.ListItemAllFields.BreakRoleInheritance(true, false);  //set folder unique permissions
folder.ListItemAllFields.RoleAssignments.Add(user, roleBindings);
ctx.ExecuteQuery();

, where folderUrl parameter corresponds to server relative url for a folder,

for example /news/documents/archive for the following structure:

News (site)
  |
  Documents (library)
     |
     Archive (folder)
查看更多
登录 后发表回答