Deleting item in SharePoint List – Avoid memory leakage
/// <summary>
/// Deletes all the items from the specifid list. Uses batch processing for performance.
/// </summary>
/// <param name="site">The site that hosts the list.</param>
/// <param name="list">The name of the list that has the items to be deleted.</param>
public static void DeleteAllItems(string site, string list)
{
using (SPSite spSite = new SPSite(site))
{
using (SPWeb spWeb = spSite.OpenWeb())
{
SPList deleteList = spWeb.Lists[list];
while (deleteList.ItemCount > 0)
{
SPQuery query = new SPQuery();
query.RowLimit = 500;
SPListItemCollection collListItems = deleteList.GetItems(query);
StringBuilder sbDelete = BuildBatchDeleteCommand(deleteList, collListItems);
spWeb.ProcessBatchData(sbDelete.ToString());
deleteList.Update();
}
}
}
}
private static StringBuilder BuildBatchDeleteCommand(SPList spList, SPListItemCollection collListItems)
{
StringBuilder sbDelete = new StringBuilder();
sbDelete.Append("<?xml version=\"1.0\" encoding=\"UTF-8\"?><Batch>");
string command = "<Method><SetList Scope=\"Request\">" + spList.ID +
"</SetList><SetVar Name=\"ID\">{0}</SetVar><SetVar Name=\"Cmd\">Delete</SetVar></Method>";
foreach (SPListItem item in collListItems)
{
sbDelete.Append(string.Format(command, item.ID.ToString()));
}
sbDelete.Append("</Batch>");
return sbDelete;
}
Comments
Post a Comment