In this blog, you will see how to get all the subsites from a site collection in SharePoint Online, using CSOM. Please refer to my previous article Connect To SharePoint 2013 Online Using CSOM With Console Application.
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;
- //Get the user's password as a SecureString
- 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)
- {
- // ClienContext - Get the context for the SharePoint Online Site
- using (var clientContext = new ClientContext(path))
- {
- // SharePoint Online Credentials
- clientContext.Credentials = new SharePointOnlineCredentials(userName, password);
- // Get the SharePoint web
- Web web = clientContext.Web;
- clientContext.Load(web, website => website.Webs, website => website.Title);
- // Execute the query to the server
- clientContext.ExecuteQuery();
- // Loop through all the webs
- foreach (Web subWeb in web.Webs)
- {
- // Check whether it is an app URL or not - If not then get into this block
- if (subWeb.Url.Contains(path))
- {
- string newpath = subWeb.Url;
- GetAllSubWebs(newpath, userName, password);
- Console.WriteLine(subWeb.Title + "-------" + subWeb.Url);
- }
- }
- }
- }
- }
- }

Murali KrisPosted Jul 9, 2018, 5:49 AM
Error: Field or property "Url" does not exist.
vanshika pandeyPosted Feb 9, 2018, 6:08 AM
What is path in the line (subWeb.Url.Contains(path)) ?