SharePoint, remove all permissions from a document or list item

April 28, 2017 1 min to read
Share

This chunk of code is for use with care, it would be useful in case you have a logic behind a scene which assigns specific permissions depending on your logic.

You have to be in elevated Privileges mode to run this code.

 

private void RemoveAllPermissions(SPListItem CurrentlistItem)
{
Guid siteId = CurrentlistItem.Web.Site.ID;
Guid webId = CurrentlistItem.Web.ID;
Guid listId = CurrentlistItem.ParentList.ID;
int itemId = CurrentlistItem.ID;
SPUserToken token = CurrentlistItem.Web.Site.SystemAccount.UserToken;

//run role removal under new instance of the site running with system privileges for security
using (SPSite site = new SPSite(siteId, token))
{
using (SPWeb web = site.OpenWeb(webId))
{
//re-fetch the item
SPList list = web.Lists[listId];
SPListItem item = list.GetItemById(itemId);

//break role inheritance and remove all roles
item.BreakRoleInheritance(true);
web.AllowUnsafeUpdates = true;

SPRoleAssignmentCollection SPRoleAssColn = item.RoleAssignments;
for (int i = SPRoleAssColn.Count – 1; i >= 0; i–)
{
SPRoleAssColn.Remove(i);
}
}
}
}

Discover more from SamTech 365

Subscribe now to keep reading and get access to the full archive.

Continue reading