Bulk deletion of SPListItems (SPListItemCollection)

A few days ago I had to develop a TimerJob that deletes a large number of items from a SharePoint list. My first idea was to iterate trough the list items and then call the delete method of the items that needed to be deleted.
Doing this was a major performance set back because it took too long to perform this action.

I went searching for another solution and I found one on the blog of The kid.

A SPWeb object has a method called: ProcessBatchData() that processes a specified batch string of commands for sending multiple requests to the server per transaction.

You can build a batch string to delete all of the items from a SharePoint list like this:

 //create new StringBuilder
 StringBuilder batchString= new StringBuilder();

 //add the main text to the stringbuilder
 batchString.Append("<?xml version=\"1.0\" encoding=\"UTF-8\"?><Batch>");

 //add each item to the batch string and give it a command Delete
 foreach (SPListItem item in itemCollection)
 {
    //create a new method section
    batchString.Append("<Method>");
    //insert the listid to know where to delete from
    batchString.Append("<SetList Scope=\"Request\">" + Convert.ToString(item.ParentList.ID) + "</SetList>");
    //the item to delete
    batchString.Append("<SetVar Name=\"ID\">" + Convert.ToString(item.ID) + "</SetVar>");
    //set the action you would like to preform 
    batchString.Append("<SetVar Name=\"Cmd\">Delete</SetVar>");
    //close the method section
    batchString.Append("</Method>");
 }

 //close the batch section
 batchString.Append("</Batch>");

 //preform the batch
 SPContext.Current.Web.ProcessBatchData(batchString.ToString()); 

The only disadvantage that I can think of right know is that all the items you delete will be put in the recycle bin. So if you perform the deletion more than ones you have to be careful with your storage quota.

You can get around that disadvantage by adding the following lines of code. The first section before the batch deletion and the other section after the deletion.

//get the recyclebinenabled status
 bool IsRecycleBinEnabled = SPContext.Current.Web.Site.WebApplication.RecycleBinEnabled;

 if(IsRecycleBinEnabled)
 {
    //set the use off the recyclebin to false
    SPContext.Current.Web.Site.WebApplication.RecycleBinEnabled = false;
 }

 //preform batch deletion

 //set the use off the recyclebin to true
 if(IsRecycleBinEnabled)
 {
    //set the use off the recyclebin to false
    SPContext.Current.Web.Site.WebApplication.RecycleBinEnabled = true;
 } 

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.