Reputation: 5050
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!
Upvotes: 8
Views: 25538
Reputation: 29
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)
}
Upvotes: 0
Reputation:
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
Upvotes: 3
Reputation: 789
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();
}
Upvotes: 8
Reputation: 13699
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:
Upvotes: 1