In some cases, we may need to copy List Items from one list
to another list including the Permissions. So while copying the ListItem to the
new List, by Default Parent permissions will be inherited to the newly created
Items which is called as Role Inheritance. To copy the unique permissions also, first we need to break the Role Inheritance
and copy the permissions as well.
Below is the simple example, where we have same lists resides in two different
site collections and now we are copying the Unique permissions from one list to
another list.
class Program { static void Main(string[] args) { try { Console.Write("Source Site URL:"); string srcSiteUrl = Console.ReadLine(); Console.Write("Source List Name:"); string srcListName = Console.ReadLine(); Console.Write("Target Site URL:"); string tgtSiteUrl = Console.ReadLine(); Console.Write("Target List Name:"); string tgtListName = Console.ReadLine(); using (SPSite srcSite = new SPSite(srcSiteUrl)) { SPWeb srcWeb = srcSite.OpenWeb(); SPList srcList = srcWeb.Lists[srcListName]; CollectionitemCollecInfo = srcList.GetItemsWithUniquePermissions(); if (itemCollecInfo.Count > 0) { using (SPSite tgtSite = new SPSite(tgtSiteUrl)) { SPWeb tgtWeb = tgtSite.OpenWeb(); SPList tgtList = tgtWeb.Lists[tgtListName]; foreach (SPListItemInfo itemInfo in itemCollecInfo) { SPListItem srcItem = srcList.GetItemById(itemInfo.Id); SPListItem tgtItem = tgtList.GetItemById(itemInfo.Id); foreach (SPRoleAssignment roleAssign in srcItem.RoleAssignments) { SPSecurity.RunWithElevatedPrivileges(delegate { if (tgtItem != null) { tgtItem.BreakRoleInheritance(false); tgtItem.RoleAssignments.Add(roleAssign); Console.WriteLine("Item ID: " + tgtItem.ID + " Roles Copied: " + roleAssign.Member); } }); } } } } } Console.ReadLine(); } catch (Exception ex) { Console.WriteLine("Error Occurred: " + ex.Message); Console.ReadLine(); } } }
No comments:
Post a Comment