views:

2205

answers:

4

I am looking for a clear, complete example of programmatically deleting all documents from a specific document library, via the Sharepoint object model. The doclib does not contain folders. I am looking to delete the documents completely (ie I don't want them in the Recycle Bin).

I know of SPWeb.ProcessBatchData, but somehow it never seems to work for me.

Thanks!

+2  A: 

You just have to go through all the files of your Document Library.

foreach(SPListItem item in SPContext.Current.Web.Lists["YourDocLibName"].Items)
{
    //TODO: Verify that the file is not checked-out before deleting
    item.File.Delete();
}

Calling the delete method on a file from the API doesn't use the recycle bin. It's a straight delete. You still need to verify that the file is not checked-out.

Here is some reference:

Maxim
too slow. Use ProcessBatchData()
vitule
+7  A: 

I would persevere with the ProcessBatchData approach, maybe this will help:

Vincent Rothwell has covered this best: http://blog.thekid.me.uk/archive/2007/02/24/deleting-a-considerable-number-of-items-from-a-list-in-sharepoint.aspx

Otherwise I'm not sure the other recommendation will work, as a Foreach loop will not like that the number of items in the collection changes with each delete.

You are probably best placed doing a reverse for loop (I didn't test this code, just an example):

for (int i = SPItems.Length - 1; i >= 0; i--)
{
    SPListItem item = SPItems[i];
    item.File.Delete();
}
Daniel McPherson
while(list.Items.Count>0){list.Items[list.Items.Count-1].File.Delete();}
Nat
The ProcessBatchData() approach is faster by several orders of magnitute.
vitule
I never got ProcessBatchData to function properly.
Paul Lalonde
A: 

This is not the right way of deleting items. Follow post here http://praveenbattula.blogspot.com/2009/05/deleting-list-items-at-time-from-list.html

A: 

Why not delete the document library and recreate it? I guess that is the fastest way of deleting all documents from a document library

Robin Meuré