Change SharePoint list item permissions to Read only programmatically

It’s a simple task but keeps slipping my mind, so I though it’s better to save it in the public diary.

So I have a Projects and Tasks master detail lists. When a project is complete, it should become read only together with all its tasks. If it was for only the Project list, I could use the SharePoint designer workflow to change the item permissions.

My projects and tasks lists have ‘Contribute’ and a custom permissions level called ‘Contribute without delete’ assigned to multiple user groups. And I wanted to change all the Contribute access to Read  access upon completion of the project.

Here’s the function I wrote,

public void MakeItemReadonly(SPWeb web, SPListItem item, string permissionToReplace, bool exactMatchOnly)
            List<SPPrincipal> principals = new List<SPPrincipal>();
            foreach (SPRoleAssignment roleAss in item.RoleAssignments)
                foreach (SPRoleDefinition roleDef in roleAss.RoleDefinitionBindings)
                    // condition based on the flag exactMatchOnly 
                    if ((exactMatchOnly?string.Compare(roleDef.Name,permissionToReplace,true)==0: roleDef.Name.Contains(permissionToReplace)))


            SPRoleAssignment assignment;
            SPRoleDefinition role = web.RoleDefinitions.GetByType(SPRoleType.Reader);
            foreach (SPPrincipal principal in principals)
                // remove the role assignment 

                // Now add the read role to the same principal 
                assignment = new SPRoleAssignment(principal);

And called the above function the following way,

MakeItemReadonly(web, listItem, "Contribute", false);
  1. Leave a comment

Leave a Reply

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

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

Google photo

You are commenting using your Google 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 )

Connecting to %s

%d bloggers like this: