In this article, let us see, how to Break the Role Inheritance and Assign Permissions to the SharePoint Lists Programmatically using C# CSOM.
By Default, when I create a List, the permission will be inherited from the Parent Web.
We need to “Stop Inheriting Permissions” and give permissions only the required group or users.
Let us see, how to do that, programmatically.
public static void BreakPermissions()
{
OfficeDevPnP.Core.AuthenticationManager authMgr = new OfficeDevPnP.Core.AuthenticationManager();
string siteUrl = "https://******.sharepoint.com/sites/DeveloperSite/";
string userName = "Sathish@********.onmicrosoft.com";
string password = "**********";
using (var ctx = authMgr.GetSharePointOnlineAuthenticatedContextTenant(siteUrl, userName, password))
{
Web web = ctx.Web;
ctx.Load(web.Lists);
ctx.Load(web);
ctx.ExecuteQueryRetry();
List list = web.Lists.GetByTitle("MyList");
ctx.Load(list);
ctx.ExecuteQuery();
list.BreakRoleInheritance(false, true);
list.AddPermissionLevelToUser("User1@****.Onmicrosoft.com", "Read", false);
list.Update();
ctx.ExecuteQuery();
System.Console.WriteLine(Convert.ToString(list.HasUniqueRoleAssignments));
}
}
After the Code Execution, the permission screen looks like below.
The Same applies to the Folder as well.
Folder projectFolder =
web.GetFolderByServerRelativeUrl( "/sites/MySite/MyList/MyFolder”);
clientContext.Load(projectFolder);
clientContext.ExecuteQuery();
projectFolder.ListItemAllFields.BreakRoleInheritance(false, true);
projectFolder. ListItemAllFields.AddPermissionLevelToUser("User1@****.Onmicrosoft.com", "Read", false);
In the same manner, we can add Permission Level the Groups as well.
projectFolder.ListItemAllFields.AddPermissionLevelToGroup("MyGroup", "Read", false);
Note: There is no method available to break the permission and assign for Item Level in PNP. (At least by the time of writing this article). Probably, if it is released in the upcoming versions, we can update this section.
Happy Coding,
Sathish Nadarajan.
Leave a comment