为什么这段代码会导致一个无限循环

本文关键字:一个 无限循环 代码 为什么 段代码 | 更新日期: 2023-09-27 18:27:20

我不得不使用CSOM打印sharepoint网站下的子网站列表。我使用了这段代码和我的服务器凭据,但我在foreach循环的第二行进入了一个无限循环。线路为

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)
         {                
         }           
     }

需要对哪些代码进行更改才能检索子网站?

为什么这段代码会导致一个无限循环

您正在将子例程添加到变量主路径中。

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)
    {          
    }           
}

这导致了一个无限循环,因为你总是在同一条路线上循环。例如:

主路径="http://triad102:1001"

  1. 首先循环您的newPath将是"http://triad102:1001/subroute"
  2. 然后,您将使用Mainpath调用getSubWebs,它将在1处递归启动。)

将您的子例程添加到这样的路径:

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)
    {          
    }           
}