Pedro Pertino
Pedro Pertino

Reputation: 95

Sharepoint delete files from documents library

I don't know what I'm doing wrong, I can't delete files, I'm working with a console application, the method SPFile.Delete() does nothing.

Here is some code:

for (int ii = web.Folders[url + documentsfolder].ItemCount - 1; ii >= 0; ii--)
                        {
                            SPFile file = web.GetFile(web.Folders[url + documentsfolder].Files[ii].UniqueId);
                            if (file.Exists)
                            {
                                file.Delete();
                            }

                        }

It doesn't throw an exception. It just stops in the first file, I don't know why.

Hope you can help

Upvotes: 0

Views: 1944

Answers (1)

user851316
user851316

Reputation: 29

Hi Here is the code snippet for Deleting folders or files of shared Documents. This might give you clue for using proper command DeleteItemById for deletion.

$web = Get-SPWeb -Identity "http://sharepoint2010/myweb/"
$list = $web.GetList("http://sharepoint2010/myweb/Shared%20Documents/")

function ProcessFolder {
    param($folderUrl)
    $folder = $web.GetFolder($folderUrl)
    foreach ($file in $folder.Files) {

        #Delete file by deleting parent SPListItem
        $list.Items.DeleteItemById($file.Item.Id)
    }
}

#Collect files to delete
ProcessFolder($list.RootFolder.Url)
#Download files in folders
foreach ($folder in $list.Folders) {
    ProcessFolder($folder.Url)
}

#Delete folders
foreach ($folder in $list.Folders) {
    try {
        $list.Folders.DeleteItemById($folder.ID)
    }
    catch {
        #Deletion of parent folder already deleted this folder
        #I really hate this
    }
}

Upvotes: 2

Related Questions