In C# CSOM How to Delete Folders Recursively, Sub-Folders, Files in SharePoint Online Document Library


In this article we will see how to delete Root folder, sub-folders, files in SharePoint Document Library. 

Here I have given snippet by hardcoding (not recommended) one folder name "TestFolder1". 

However you can use loop statement and iterate list of root folder names. 


var clientContext = GetClientContextWithAccessToken(siteUrl, accessToken);
Web web = clientContext.Web;
clientContext.Load(web);
clientContext.ExecuteQuery();

//Here you can add for loop with list of root folder names and iterate
//Start of for loop
string folderPath = "/sites/contoso5/LibraryName/TestFolder1"; //Pass the folder name dynamically
Folder folder = clientContext.Web.GetFolderByServerRelativeUrl(folderPath);
clientContext.Load(folder, folderitem => folderitem.Properties, folderitem => folderitem.Name, folderitem => folderitem.Files);
clientContext.ExecuteQuery();
DeleteFolderRecursive(folder); //Call method to delete subfolders and files.
folder.DeleteObject();
clientContext.ExecuteQuery();
//End of for loop

//This method will delete all subfolders and files in the given folder
private static void DeleteFolderRecursive(Folder folder)
{
    using(ClientContext ctx = (ClientContext)folder.Context)
    {
      ctx.Load(folder);
      ctx.ExecuteQuery();
      FileCollection files = folder.Files;
      ctx.Load(files);
      ctx.ExecuteQuery();
      File[] filesArray = new File[files.Count];
      filesArray = files.ToArray();
      foreach(File file in filesArray)
      {
         file.DeleteObject();
      }

      FolderCollection subfolders = folder.Folders;
      ctx.Load(subfolders);
      ctx.ExecuteQuery();

      Folder[] subfoldersArray = new Folder[subfolders.Count];
      subfoldersArray = subfolders.ToArray();
      foreach(Folder subfolder in subfoldersArray)
      {
         DeleteFolderRecursive(subfolder);
         subfolder.DeleteObject();
      }

      ctx.Load(folder);
      ctx.ExecuteQuery();
   }
}


Happy PC (Programming / Configuring)

Comments

Popular posts from this blog

How Get, Set, Delete Permission on SharePoint Online Site using Graph API

What is SharePoint online default authentication method? And which credential flow it is using to authenticate?