You are using O365 for your SharePoint. You have created several Sub Sites in the process. Now you would like to delete these sub sites. But would like if these sub site deletion can be automated.
This below code snippet will delete all sub-sites in a SharePoint Online site collection. The code base is based on SharePoint Client object-model. For On-Prem you can use PowerShell, but for O365 below code is a better approach.
Details
Open Visual Studio, start a new console application with name “CA_deleteSubSites”. Paste the below code and change the variable wherever required.
using System; using System.Text; using System.Threading.Tasks; using System.Diagnostics; using System.Configuration; using System.Collections.Generic; using Microsoft.Online.SharePoint.TenantAdministration; using Microsoft.SharePoint.Client; using Microsoft.SharePoint.Client.Utilities; using System.Security; using System.IO; using System.Linq; namespace CA_deleteSubSites { classProgram { staticstring trgsiteuser = ConfigurationManager.AppSettings["trgsiteuser"]; //xxx.onmicrosoft.com user staticstring mainpath = "https://xxxx.sharepoint.com"; staticvoid Main(string[] args) { string trgsiteuserpass = ConfigurationManager.AppSettings["trgsiteuserpass"]; string path = "https://xxxx.sharepoint.com/sites/demo"; // site to be deleted SecureString passWord = newSecureString(); foreach (char c in trgsiteuserpass.ToCharArray()) passWord.AppendChar(c); deleteallSubWebs(path, passWord ); } publicstaticvoid deleteallSubWebs(string path, SecureString passWord) { try { //connect to the root site using (ClientContext clientContext = newClientContext(path)) { clientContext.Credentials = newSharePointOnlineCredentials(trgsiteuser, passWord); if (clientContext != null) { Web oWebsite = clientContext.Web; clientContext.Load(oWebsite, website => website.Webs, website => website.Title); clientContext.ExecuteQuery(); if (oWebsite.Webs.Count == 0) { Console.WriteLine(path); oWebsite.DeleteObject(); clientContext.ExecuteQuery(); Console.WriteLine("deleted.." + oWebsite.Title); } else { foreach (Web orWebsite in oWebsite.Webs) { string newpath = mainpath + orWebsite.ServerRelativeUrl; deleteallSubWebs(newpath, passWord); } Console.WriteLine(path); oWebsite.DeleteObject(); clientContext.ExecuteQuery(); Console.WriteLine("deleted.." ); } } } } catch (Exception ex) { Console.WriteLine(ex.Message); } } } }
Conclusion
Hope this will help you to delete all sub site in a site but use it with caution to ensure you know what you are about to delete!