-1

I had to print the list of the subwebsites under a sharepoint site using CSOM. i used this code and my server credentials but i go inside a infinite loop at 2nd line of foreach loop. The line is

getSubWebs(newpath);

static string mainpath = "http://triad102:1001";
     static void Main(string[] args)
     {
         getSubWebs(mainpath);
         Console.Read();
     }
     public static  void  getSubWebs(string path)
     {          
         try
         {
             ClientContext clientContext = new ClientContext( path );
             Web oWebsite = clientContext.Web;
             clientContext.Load(oWebsite, website => website.Webs, website => website.Title);
             clientContext.ExecuteQuery();
             foreach (Web orWebsite in oWebsite.Webs)
             {
                 string newpath = mainpath + orWebsite.ServerRelativeUrl;
                 getSubWebs(newpath);
                 Console.WriteLine(newpath + "\n" + orWebsite.Title );
             }
         }
         catch (Exception ex)
         {                

         }           
     }

what code changes has to be made to retrieve the subwebsites?

kaarthick raman
  • 793
  • 2
  • 13
  • 41

1 Answers1

3

You are adding your subroutes to your variable mainpath.

static string mainpath = "http://triad102:1001";

public static  void  getSubWebs(string path)
{          
    try
    {
        ...
        foreach (Web orWebsite in oWebsite.Webs)
        {
            string newpath = mainpath + orWebsite.ServerRelativeUrl; //<---- MISTAKE
            getSubWebs(newpath);
        }
    }
    catch (Exception ex)
    {          
    }           
}

This is causing a Infinite Loop, because you are always looping over the same Routes. E.g.:

Mainpath = "http://triad102:1001"

  1. First Loop your newPath will be "http://triad102:1001/subroute"
  2. Then you will invoke getSubWebs with Mainpath and it will start recursively at 1.) again.

Add your subroutes to path like that:

static string mainpath = "http://triad102:1001";

public static  void  getSubWebs(string path)
{          
    try
    {
        ...
        foreach (Web orWebsite in oWebsite.Webs)
        {
            string newpath = path + orWebsite.ServerRelativeUrl; 
            getSubWebs(newpath);
        }
    }
    catch (Exception ex)
    {          
    }           
}
B. Kemmer
  • 1,517
  • 1
  • 14
  • 32