Monday, February 18, 2008

Setting item level security in SharePoint List

SPSite NDASite = new SPSite(SITE_URL);
SPWeb NDAWeb = NDASite.OpenWeb();
SPList COIList = NDAWeb.Lists[LIST_NAME];
SPListItemCollection listItems = COIList.Items;

SPGroup Group = NDAWeb.SiteGroups["test"];
SPRoleAssignment gr = new SPRoleAssignment(Group);
SPRoleDefinition role = NDAWeb.RoleDefinitions["Contribute"];
gr.RoleDefinitionBindings.Add(role);
//For each item in the list

foreach (SPListItem item in listItems)
{
//Break inheritance
item.BreakRoleInheritance(true);

//Get SPRoleAssignmentCollection
SPRoleAssignmentCollection sr = item.RoleAssignments;
//Removeing all current permissions if needs..
for (int i = 0; i < sr.Count; i++)
{
sr.Remove(i);
}
//Add group to SPRoleAssignmentCollection
sr.Add(gr);
//gr.Update(); - no need to update
}

2 comments:

Robert St-John Smith said...

Hi,

small mistake in your code

the for next needs to be a minus

for (int i = sr.Count-1;i>-1; i--)
{
sr.Remove(i);
}

Robert St-John Smith said...
This comment has been removed by a blog administrator.