Monday, March 14, 2011

Delete All Items, including Folders, from SharePoint List Programmatically and Efficiently

From this post http://www.praveenmodi.com/programmatically-delete-all-items-sharepoint-list/ by Praveen Modi.

///
/// Purges items and folders from a list
/// Define WSSV3 to remove list folders
///

/// The SPList you want to
/// purge items from
private static void PurgeList(SPList list)
{
Console.WriteLine("Purging list: " + list.Title);
Console.WriteLine("Base Type: " + list.BaseType.ToString());

// ===========================================================
// list.ItemCount returns a count that includes all items
// "AND" folders.
// You can't use list.Items.DeleteItemById() to remove a
// folder
// ===========================================================
System.Collections.Hashtable hItems =
new System.Collections.Hashtable(list.ItemCount);

// ===========================================================
// SPList.Items returns all list items in the entire list
// regardless of folder containment
// Note, just because list.ItemCount includes folders,
// list.Items does not.
// ===========================================================
foreach (SPListItem item in list.Items)
hItems.Add(item.ID,null);

// Remove the list items
foreach (int ID in hItems.Keys)
list.Items.DeleteItemById(ID);
// Clear the hashtable
hItems.Clear();
// ===========================================================
// SPList.Folders returns all folder items in the entire list
// regardless of parent folder containment
// ===========================================================
foreach (SPListItem item in list.Folders)
hItems.Add(item.ID,null);

// Remove the folder items
foreach (int ID in hItems.Keys)
{
list.Folders.DeleteItemById(ID);
}
}

No comments:

Post a Comment