为什么这段代码导致无限循环?

时间:2015-12-18 09:14:15

标签: c# timeout sharepoint-2013 csom request-timed-out

我必须使用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)
         {                

         }           
     }

必须进行哪些代码更改才能检索子网站?

1 个答案:

答案 0 :(得分:3)

您正在将子路径添加到变量主路径

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

这会导致无限循环,因为您始终循环遍历相同的路由。例如:

Mainpath = "http://triad102:1001"

  1. 首先循环 newPath 将为"http://triad102:1001/subroute"
  2. 然后你将使用Mainpath调用getSubWebs,它将在1.)以递归方式启动。
  3. 将子路径添加到路径中:

    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)
        {          
        }           
    }
    
相关问题