Bulk deleting sharepoint list items – use SPWeb.ProcessBatchData

For most developers the obvious solution would be to use something like:

foreach (SPListItem item in list.Items)
{
item.Delete();
}

That’s probably fine for small lists.  However when you need to delete anything over say 10 items then it would be better to provide a batch command to SharePoint.  This way with just one batch update you could delete any x number of items based on their item id in the the list or even empty the list completely:

batchString.Append(“”);
foreach (SPListItem item in splic)
{
batchString.Append(“”);
batchString.Append(“” + Convert.ToString(item.theList.ID) + “”);
batchString.Append(“” + Convert.ToString(item.ID) + “”);
batchString.Append(“Delete”);
batchString.Append(“”);
}
batchString.Append(“”);
web.ProcessBatchData(batchString.ToString());

Access content as system user – SPSecurity.RunWithElevatedPrivileges

Any code behind in SharePoint defaults to run as the current logged on user on the site. However this can become an issue if you want to programmatically update/access content that the user does not have permission to. For instance on the code behind of a layout page or workflow.

To get around this you need to run the code under ‘elevated privileges‘ following the example below:

 

SPSecurity.RunWithElevatedPrivileges(delegate()

{

using (SPSite site = new SPSite(web.Site.ID))

{

// write your code here

}

});