Often when you’re developing or testing out a new feature you need a way to quickly purge all items from a list.  If you’re only working with a handfull of list items, iterating through the list one item at a time may work sufficiently for you, but if you’re working with a list containing several thousand or possibly tens of thousands of items you’ll quickly discover that you need a more efficient method for this.  SharePoint allows for you to submit batch jobs for processing.  Here’s a quick example for batch deleting all the items in the list.

using (SPSite site = new SPSite(SITEURL))
{
	using (SPWeb web = site.OpenWeb())
	{
		var list = web.Lists[LISTNAME];
		
		StringBuilder sbDelete = new StringBuilder();
		sbDelete.Append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
		sbDelete.Append("<Batch>");
		
		string command = "<Method><SetList Scope=\"Request\">" + list.ID + 
				 	"</SetList><SetVar Name=\"ID\">{0}</SetVar>" +
				 	"<SetVar Name=\"Cmd\">Delete</SetVar></Method>";

		foreach (SPListItem item in list.Items)
		{ 
			sbDelete.Append(string.Format(command, item.ID.ToString()));
		}
		
		sbDelete.Append("</Batch>");
		
		web.ProcessBatchData(sbDelete.ToString());
		
		web.RecycleBin.DeleteAll();
	}
}

Posted by Chris Buchanan

Leave a reply

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