`
How To Get All Subsites From A Site Collection In SharePoint Online Using CSOM
In this blog, you will learn how to get all subsites from a site collection in SharePoint Online, using CSOM.
Code Snippet
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Net;
- using System.Security;
- using System.Text;
- using System.Threading.Tasks;
- using Microsoft.SharePoint.Client;
-
- namespace GetAllSubsites
- {
- class Program
- {
- static void Main(string[] args)
- {
- string userName = "[email protected]";
- string siteURL = "https://c986.sharepoint.com/sites/Vijai";
- Console.WriteLine("Enter your password.");
- SecureString password = GetPassword();
- GetAllSubWebs(siteURL, userName, password);
- Console.ReadLine();
-
- }
-
- private static SecureString GetPassword()
- {
- ConsoleKeyInfo info;
-
- SecureString securePassword = new SecureString();
- do
- {
- info = Console.ReadKey(true);
- if (info.Key != ConsoleKey.Enter)
- {
- securePassword.AppendChar(info.KeyChar);
- }
- }
- while (info.Key != ConsoleKey.Enter);
- return securePassword;
- }
-
- private static void GetAllSubWebs(string path, string userName, SecureString password)
- {
-
- using (var clientContext = new ClientContext(path))
- {
-
- clientContext.Credentials = new SharePointOnlineCredentials(userName, password);
-
-
- Web web = clientContext.Web;
- clientContext.Load(web, website => website.Webs, website => website.Title);
-
-
- clientContext.ExecuteQuery();
-
-
- foreach (Web subWeb in web.Webs)
- {
-
- if (subWeb.Url.Contains(path))
- {
- string newpath = subWeb.Url;
- GetAllSubWebs(newpath, userName, password);
- Console.WriteLine(subWeb.Title + "-------" + subWeb.Url);
- }
- }
- }
- }
- }
- }