Delete a Sharepoint Folder using ClientContext if it is empty

14.10.2019
|
0 Comments
||
|

Delete a Sharepoint Folder using ClientContext if it is empty

To delete a Sharepoint Folder, it should be empty otherwise it will not allow us to delete it. So before deleting the folder we need to check if it is empty or not.

Below is the code in .NET (C#)

 // Get the context variable of site
OfficeDevPnP.Core.AuthenticationManager authMgr = new OfficeDevPnP.Core.AuthenticationManager();
using (var ctx = authMgr.GetSharePointOnlineAuthenticatedContextTenant(_siteUrl, _userId, _password))
{
       try
      {
             // Load the Sharepoint Documents
            Web web = ctx.Web;
            List list = web.Lists.GetByTitle("Documents");
            ctx.Load(list);
            ctx.ExecuteQueryRetry();
            // Get the Folder using its Relative Path
            string temp = folderRelativePath.Replace(WebConfigurationManager.AppSettings["SiteUrl"] + "/Shared Documents/", "").Trim();
            var folderToDelete = web.GetFolderByServerRelativeUrl(web.ServerRelativeUrl + "/Shared%20Documents/" + temp);
             // Count the files/items inside the Folder
            ctx.Load(folderToDelete, f => f.ItemCount);
            ctx.ExecuteQuery();
            // Just to create Log to check how many files it has
            using (StreamWriter writer = new StreamWriter(HttpContext.Current.Server.MapPath("~/log.txt"), true))
            {
   	writer.WriteLine("Folder file count="+ folderToDelete.ItemCount);
            }
            // Checking if folder contains any file
            if (folderToDelete.ItemCount <= 0)
            {
	// Deleting the Folder
   	folderToDelete.DeleteObject();   
   	ctx.ExecuteQuery();
             }
     }
      // Catch in case of any exception
       catch (Exception ex)
       {    
             // Log the Exception for the debugging purpose.
            using (StreamWriter writer = new StreamWriter(HttpContext.Current.Server.MapPath("~/log.txt"), true))
           {
                 writer.WriteLine("Error in Deleting Folder=="+ ex.Message);
           }
           return Request.CreateResponse(HttpStatusCode.InternalServerError, ex.Message);
      }
}

Leave a Reply

Your email address will not be published. Required fields are marked *

Share on:
Share this...
Share on Facebook
Facebook
Tweet about this on Twitter
Twitter
Share on LinkedIn
Linkedin
Website security
Contact Us