2007-08-31

Recursive batch delete command

We all know the scenario: we have a list with a large number of junk testing records we need to get rid of.

We could write a console app with the following:

SPListItemCollection listItems = list.Items;
for (int id = 8; id <= listItems.Count; id++)
{
try {
listItems[id].Delete();
Console.WriteLine("Deleting " + id.ToString());
}
catch(Exception ex){ }
}
list.Update();



Now sit back and watch the numbers tick by... or you could what is widely considered the fastest way in SharePoint (WSS) to perform the operation, to use 'ProcessBatchData' as it avoids the Object Model and is considerably faster.

Here is some example code which will remove items from a SharePoint list.

StringBuilder oSBDelBat = new StringBuilder();
oSBDelBat.Append("<?xml version=\"1.0\" encoding=\"UTF-8\"?><batch>");
foreach (SPListItem item in CurrentList.Items)
{
oSBDelBat.Append("<method>");
oSBDelBat.Append("<setlist scope="\">" + CurrentList.ID + "</setlist>");
oSBDelBat.Append("<setvar name="\">" + Convert.ToString(item.ID) + "</setvar>");
oSBDelBat.Append("<setvar name="\">Delete</setvar>");
oSBDelBat.Append("</method>");
}
oSBDelBat.Append("</batch>");
try
{
SPContext.Current.Site.RootWeb.ProcessBatchData(oSBDelBat.ToString());
}
catch (Exception ex)
{
Console.WriteLine("Delete failed: " + ex.Message);
throw;
}


No comments :

Post a comment