How to change permissions of specific Sub ListItem in OneDrive for Business with CSOM

If you want to apply custom permissions to a subfolder in a list using CSOM, hereby what to do :

Fetch the parent folder :
Here parentFolderPath, can be : “/Documents/MyParentFolder” , this is the folder who’s containing the folder on which you want to apply the permissions

List l = clientContext.Site.RootWeb.GetList(web.ServerRelativeUrl + parentFolderPath);
clientContext.Load(l);

Load all the items of the list :

ListItemCollection folderItems = l.GetItems(CamlQuery.CreateAllItemsQuery());
clientContext.Load(folderItems, items = & gt; items.Include(
item = & gt; item.Id,
item = & gt; item.DisplayName));
clientContext.ExecuteQuery();

Loop on all items until you found the items you want, and then apply the permission.
Here the code is going to add Read permission for the group Everyone

foreach(var x in folderItems) {
	Console.WriteLine(x.DisplayName);
	if (x.DisplayName.Equals(folderName) && x.Folder != null) {
		Console.WriteLine("\t found");
		var ctx = x.Context as ClientContext;
		var roleDefinition = ctx.Site.RootWeb.RoleDefinitions.GetByName("Read");
		x.BreakRoleInheritance(true, false);
		var roleBindings = new RoleDefinitionBindingCollection(ctx) {
			roleDefinition
		};
		x.RoleAssignments.Add(clientContext.Web.SiteUsers.GetById(4), roleBindings);
		ctx.ExecuteQuery();
	}
}

 

Advertisements
This entry was posted in OneDrive, SharePoint. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s