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
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Net;
  5. using System.Security;
  6. using System.Text;
  7. using System.Threading.Tasks;
  8. using Microsoft.SharePoint.Client;
  9. namespace GetAllSubsites
  10. {
  11. class Program
  12. {
  13. static void Main(string[] args)
  14. {
  15. string userName = "[email protected]";
  16. string siteURL = "https://c986.sharepoint.com/sites/Vijai";
  17. Console.WriteLine("Enter your password.");
  18. SecureString password = GetPassword();
  19. GetAllSubWebs(siteURL, userName, password);
  20. Console.ReadLine();
  21. }
  22. private static SecureString GetPassword()
  23. {
  24. ConsoleKeyInfo info;
  25. //Get the user's password as a SecureString
  26. SecureString securePassword = new SecureString();
  27. do
  28. {
  29. info = Console.ReadKey(true);
  30. if (info.Key != ConsoleKey.Enter)
  31. {
  32. securePassword.AppendChar(info.KeyChar);
  33. }
  34. }
  35. while (info.Key != ConsoleKey.Enter);
  36. return securePassword;
  37. }
  38. private static void GetAllSubWebs(string path, string userName, SecureString password)
  39. {
  40. // ClienContext - Get the context for the SharePoint Online Site
  41. using (var clientContext = new ClientContext(path))
  42. {
  43. // SharePoint Online Credentials
  44. clientContext.Credentials = new SharePointOnlineCredentials(userName, password);
  45. // Get the SharePoint web
  46. Web web = clientContext.Web;
  47. clientContext.Load(web, website => website.Webs, website => website.Title);
  48. // Execute the query to the server
  49. clientContext.ExecuteQuery();
  50. // Loop through all the webs
  51. foreach (Web subWeb in web.Webs)
  52. {
  53. // Check whether it is an app URL or not - If not then get into this block
  54. if (subWeb.Url.Contains(path))
  55. {
  56. string newpath = subWeb.Url;
  57. GetAllSubWebs(newpath, userName, password);
  58. Console.WriteLine(subWeb.Title + "-------" + subWeb.Url);
  59. }
  60. }
  61. }
  62. }
  63. }
  64. }