Quantcast
Channel: SharePoint Diary
Viewing all articles
Browse latest Browse all 1058

Delete Folders, Sub-Folders from SharePoint Library Programmatically

$
0
0
I need to delete a Folder from SharePoint 2010 document library using object model programmatically. Here is the code to delete the sub-folder from SharePoint document library:

To Delete a Sub-folder from SharePoint Document Library Programmatically:
            String siteURL = "http://sharepoint.crescent.com/sites/sales"; 
            String listName = "Documents";
            String folderToDelete = "v2";

            using (SPSite site = new SPSite(siteURL))
            {
                using (SPWeb web = site.OpenWeb())
                {
                    SPFolderCollection folders = web.Folders[listName].SubFolders;

                    foreach (SPFolder folder in folders)
                    {
                        if (folder.Name == folderToDelete)
                        {
                           web.Folders[listName].SubFolders.Delete(folder.Url);
                        }
                    }                    
                }
            }

The above code can be converted to PowerShell also, to delete folders programmatically: 
 Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue
        $siteURL = "http://sharepoint.crescent.com/sites/sales.com"
        $listName = "Documents"
        $folderToDelete = "v2"
  #Get the Web
        $web = Get-SPWeb $siteURL  
  #Get all Sub folders
  $folders = $web.Folders[$listName].SubFolders

                    Foreach ($folder in $folders)
                    {
                        if ($folder.Name -match $folderToDelete)
                        {
        $web.Folders[$listName].SubFolders.Delete($folder);
          Write-Host "Folder has been deleted!"
                        }
                    }                    


If you want to Delete All Folders from a Library:
 Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue
     $siteURL = "http://sharepoint.crescent.com/sites/sales"
           $listName = "Documents"
         #Get the Web
                $web = Get-SPWeb $siteURL  
  #Get the list
  $list = $web.lists[$listName]
  #Get all folders under the list
  $query =  New-Object Microsoft.SharePoint.SPQuery
  $camlQuery = '<Where><Eq><FieldRef Name="ContentType" /><Value Type="Text">Folder</Value></Eq></Where>'

  $query.Query = $camlQuery
  $query.ViewAttributes = "Scope='RecursiveAll'"
  $folders = $list.GetItems($query)

  for ($index = $folders.Count - 1; $index -ge 0; $index--)
  {
   Write-Host("Deleting folder: $($folders[$index].Name) at $($folders[$index].URL)")
      $folders.Delete($index);
  }

Related Post: Create Folders and Sub-Folders in SharePoint Programmatically

Viewing all articles
Browse latest Browse all 1058

Trending Articles