Thursday, February 25, 2010

C# Copy the Permissions from one list to another list in SharePoint

Today I have got a requirement to copy the permission from existing list and Create a new list with the permissions inherited from existing list programmatically.

Here is code which is very simple will make you better understanding .

using (SPSite spSite = new SPSite("http://servername:Portnumber/"))
{
using (SPWeb spWeb = spSite.OpenWeb())
{
SPList spList = spWeb.Lists["AgeRating"];

//Get all roles from the existing list
SPRoleAssignmentCollection coll = spList.RoleAssignments;

SPListCollection lists = spWeb.Lists;

// create new Generic list called "MyList"

if (!spWeb.Lists.Cast().Any(list => string.Equals(list.Title, "MyList")))
{
spWeb.AllowUnsafeUpdates = true;
lists.Add("MyList", "My list Description", SPListTemplateType.GenericList);
spWeb.AllowUnsafeUpdates = false;
}

SPList targetList = spWeb.Lists["MyList"];
foreach (SPRoleAssignment role in coll)
{
targetList.BreakRoleInheritance(false);
spWeb.AllowUnsafeUpdates = true;
targetList.RoleAssignments.Add(role);
}

spWeb.AllowUnsafeUpdates = false;
}
}

2 comments:

digital certificates said...

Grateful to check out your website, I seem to be ahead to more excellent sites and I wish that you wrote more informative post for us. Well done work.

Anonymous said...

Hello RajKamal,
Is this within the same site? Can you please give details on where to put new list name and so on.