I am trying to assign permissions to document library via C# CSOM

Below is the code that I am using

public string AssignPermission(ClientContext ctx, string[] accountName, string folderUrl,RoleType role) {
                foreach (string userid in accountName)
                    if (userid.Length > 0) { 
                        User user = ctx.Web.EnsureUser(userid);
                        Folder folder = ctx.Web.GetFolderByServerRelativeUrl(folderUrl);
                        var roleDefinition = ctx.Site.RootWeb.RoleDefinitions.GetByType(role);  //get Reader role
                        var roleBindings = new RoleDefinitionBindingCollection(ctx) { roleDefinition };
                        folder.ListItemAllFields.BreakRoleInheritance(false, true);  //set folder unique permissions
                        folder.ListItemAllFields.RoleAssignments.Add(user, roleBindings);
                return "Permission Assigned";
            catch (Exception ex)
                return ex.Message;

The code usage is like below

AssignPermission(context, userids, folderUrl, RoleType.Reader);

The problem I am facing is, even if I give RoleType.Reader, it is assigning only full control permission for the user


Here is an example which creates a folder in a library, breaks the permissions and assigns Contributor role to the user. You can modify it per your needs.

using (var clientContext = new ClientContext("http://aissp2013:90"))
  Site site = clientContext.Site;                
  Web web = clientContext.Web;
  List list = web.Lists.GetByTitle("Documents");
  Folder newFolder = list.RootFolder.Folders.Add("F4");
  newFolder.ListItemAllFields.BreakRoleInheritance(false, true);
  var role = new RoleDefinitionBindingCollection(clientContext);
  User user = web.EnsureUser("contoso\\adamb");
  newFolder.ListItemAllFields.RoleAssignments.Add(user, role);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.