Delete Sub Site from SharePoint using CSOM (PnP Core Component)

PnP core component contains the extension methods which help to achieve the SharePoint task in simple lines of code. So to know more about PnP Core component, have a look at “Introduction to PnP Core Component”.

WebExtensions.DeleteWeb (PnP Core Component) – This extension method first checks the subsite available in the specified url and then delete that subsite from the parent web.

Method

boolDeleteWeb(stringsubsiteUrl)


Parameters:

Parameter Type Description
subsiteUrl string A string that represents the URL leaf name of a subsite


Return Type Description
bool true if the web was deleted; otherwise false if nothing was done

Syntax:

Single Line Code: Web.DeleteWeb("subsiteurl")

Code Snippet

The following example deletes the subsite from the parent website based on the given url and returns true value. If the subsite is not available or there's a problem in deleting the child site, this method returns false.

  • Create a console application.

  • Add PnP core component assembly references to the application. Refer “Introduction to PnP Core Component” to add a references to the VS solution.

  • Add Using Microsoft.SharePoint.Client and Using OfficeDevPnP.Core.Extensions as using statement to the top of the file.

  • Add the below code snippet and change the values where ever necessary. 
  1. using System;  
  2. usingSystem.Collections.Generic;  
  3. usingSystem.Linq;  
  4. usingSystem.Text;  
  5. usingSystem.Threading.Tasks;  
  6. usingMicrosoft.SharePoint.Client;  
  7. usingOfficeDevPnP.Core;  
  8. // Assembly Reference Used: OfficeDevPnP.Core, Version=2.4.1605.0, Culture=neutral, PublicKeyToken=3751622786b357c2  
  9. //Supports SharePoint Online, SharePoint 2013+  
  10. namespaceSampleApplication  
  11. {  
  12.     classProgram  
  13.     {  
  14.         staticvoid Main(string[] args)  
  15.         {  
  16.             stringsiteUrl = "https://sharepointonline.sharepoint.com";  
  17.             AuthenticationManagerauthManager = newAuthenticationManager();  
  18.             //Interactive Login to SharePoint site - Opens a Online signin page to authenticate the user  
  19.             var context = authManager.GetWebLoginClientContext(siteUrl);  
  20.             //Deletes the child website with the specified subsite URL, from a parent Web, if it exists. Else the method return false value.  
  21.             bool success = context.Web.DeleteWeb("subsiteurl");  
  22.             if (success)  
  23.                 Console.WriteLine("Site deleted successfully.");  
  24.             else  
  25.                 Console.WriteLine("Problem in deleting the site.");  
  26.             Console.WriteLine("Press any key to exit.");  
  27.             Console.ReadKey();  
  28.         }  
  29.     }  
  30. }  
The above codeis also available from GitHub
Ebook Download
View all
Learn
View all