1

我需要从Sharpeoint 服务器循环所有文档库,但是我在子站点的子站点失败了

首先我使用下面的方法来获取我的 SiteCollections

internal List<string> GetAllSite()
    {
        List<string> siteCollection = new List<string>();
        try
        {

            SPSecurity.RunWithElevatedPrivileges(delegate ()
            {
                SPServiceCollection services = SPFarm.Local.Services;
                foreach (SPService curService in services)
                {
                    if (curService is SPWebService)
                    {
                        SPWebService webService = (SPWebService)curService;


                        foreach (SPWebApplication webApp in webService.WebApplications)
                        {
                            foreach (SPSite sc in webApp.Sites)
                            {
                                try
                                {
                                    siteCollection.Add(sc.Url);
                                    Console.WriteLine("Do something with site at: {0}", sc.Url);
                                }
                                catch (Exception e)
                                {
                                    Console.WriteLine("Exception occured: {0}\r\n{1}", e.Message, e.StackTrace);
                                }
                            }
                        }
                    }
                }


            });
        }
        catch (Exception ex)
        {

            throw;
        }

        return siteCollection;
    }

之后,我使用返回站点集合 url 循环子站点,如下代码

 using (SPSite site = new SPSite(SiteCollectionUrl))
                {

                    foreach (SPWeb web in site.AllWebs)
                    {
                          //i get the subsite url from here

                    }

                }

现在这是我的问题,正如我之前提到的,我想获取子站点的子站点,所以我将我的子站点 url 传递给 SPSite,但是它只会循环 SiteCollections 而不是我的子站点

foreach (SPWeb web in site.AllWebs) <--我的意思是在这里,在这里只会循环我的站点集合项目,尽管我已经将我的子站点 url 作为参数传递

4

1 回答 1

0

如果您只想要给定站点的直接后代子站点,则应使用该SPWeb.Webs属性而不是该SPSite.AllWebs属性。

获取一个网站集合对象,该对象表示该网站正下方的所有网站,不包括这些网站的子网站。

using (SPSite siteCollection = new SPSite(SiteCollectionUrl))
{
    using(SPWeb parentSite = siteCollection.OpenWeb())
    {
       foreach (SPWeb subsite in parentSite.Webs)
       {
            // do something with subsite here
            subsite.Dispose();
       }
    }
    siteCollection.Dispose();
}

如果您还需要获取这些子站点的所有子站点,直到考虑到所有后代(直接和间接),您应该在循环中使用递归。

请注意,为每个子站点实例化和处置 SPWeb 对象可能会造成性能负担。

如果您不需要访问每个子网站的完整属性,最好使用网站集的AllWebs属性来获取对SPWebCollection对象的引用。然后,您可以使用该WebsInfo属性SPWebCollection来获取List<>轻量级 SPWebInfo 对象,如本答案中所述。

于 2017-03-08T22:41:50.150 回答