8

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!

Paul Lalonde
  • 5,020
  • 2
  • 32
  • 35
  • Do you have access to the WSS or MOSS environment? I am thinking a PowerShell script added either ran one time or as a scheduled task would benefit you. – websch01ar Oct 31 '08 at 20:49
  • This is for WSS. I don't think a PowerShell script would do the job, since I have to perform the deletion from within an event receiver. – Paul Lalonde Oct 31 '08 at 20:58
  • What issue you are Facing in the ProcessBatchData ? Lets us know that will be Simplest Option to do this. – Kusek Jun 18 '09 at 11:44

4 Answers4

8

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
  • 789
  • 5
  • 14
3

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

Matthew Murdoch
  • 30,874
  • 30
  • 96
  • 127
1

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:

Maxime Rouiller
  • 13,614
  • 9
  • 57
  • 107
0

Powershell way:

function ProcessFolder {
    param($folderUrl)
    $folder = $web.GetFolder($folderUrl)
    foreach ($file in $folder.Files) {
        #Ensure destination directory
        $destinationfolder = $destination + "/" + $folder.Url 
        if (!(Test-Path -path $destinationfolder))
        {
            $dest = New-Item $destinationfolder -type directory 
        }
         #Delete file by deleting parent SPListItem
        $list.Items.DeleteItemById($file.Item.Id)
    }
}

#Delete root Files
ProcessFolder($list.RootFolder.Url)

#Delete files from Folders or Document Sets
foreach ($folder in $list.Folders) {
    ProcessFolder($folder.Url)
}
Richard Gear
  • 29
  • 2
  • 9