Deleting a large number of items from a list in SharePoint
Recently the question was asked in the newsgroups about deleting a large number of items from SharePoint (WSS) in the fastest way. I had, in one if my projects, needed to remove a large number of item from SharePoint and the best way I found was to use 'ProcessBatchData' as it avoided the API and was considerably faster.
Here is some example code which will remove items from a SharePoint list. If you do this I would remember about the Recycle Bin and the effect deleting many items will have in the future...it maybe worth adding some code which also removes the items from the recycle bin once it has finished.
StringBuilder sbDelete = new StringBuilder();
sbDelete.Append("<?xml version=\"1.0\" encoding=\"UTF-8\"?><Batch>");
foreach (SPListItem item in CurrentList.Items)
{
sbDelete.Append("<Method>");
sbDelete.Append("<SetList Scope=\"Request\">" + CurrentList.ID + "</SetList>");
sbDelete.Append("<SetVar Name=\"ID\">" + Convert.ToString(item.ID) + "</SetVar>");
sbDelete.Append("<SetVar Name=\"Cmd\">Delete</SetVar>");
sbDelete.Append("</Method>");
}
sbDelete.Append("</Batch>");
try
{
SPContext.Current.Site.RootWeb.ProcessBatchData(sbDelete.ToString());
}
catch (Exception ex)
{
Console.WriteLine("Delete failed: " + ex.Message);
throw;
}
I took me some time to re-find this code and so I have posted it here more for my benefit, but if anyone finds it useful then great.