How to loop through all webs and sub webs of a SharePoint Web

谁都会走 提交于 2019-12-11 23:57:41

问题


I am trying to loop through all webs and subs-webs of those webs under a web.

My Parent web

http://EXAMPLE.com/parentweb (This is a sub site not a root web)

sub webs http://example.com/parentweb/subweb ( This is one of the sub web which may or may not have sub webs)

The only thing i tried is go to the site collection and loop throug all webs which is much longer process because i know the only sub site that needs to be checked. my site collection has multiple sub sites. i don't want to loop through all subs sites.

This code works but it takes so much of time and it loops through all subsites which don't need to be checked

     using(SPSite site = new SPSite(“http://myserver/mysitecol”) 
           { 
               foreach(SPWeb web in site.AllWebs) 
               {
               }
           } 

回答1:


You can use the .Webs property of an SPWeb object to access its direct child subsites.

using(SPSite site = new SPSite("http://myserver/mysitecol") 
{ 
    using(SPWeb parentweb = site.OpenWeb("subweb/subweb") 
    {
        foreach(SPWeb web in parentweb.Webs)
        {

        }
    }
} 

To access all (including indirect) descendant child sites below a Web, you could access that .Webs property recursively on each direct descendent, but it would be more straightforward to start with the .AllWebs property of the SPSite site collection object.

The .WebsInfo property of the SPWebCollection returned by .AllWebs gives you a List<> of lightweight SPWebInfo objects. You can use this lightweight collection to get a filtered list of the Webs you care about without having to instantiate and dispose of any of the other SPWebs in the collection.

string webUrl = "/mysitecol/subweb/subweb";
using(SPSite site = new SPSite("http://myserver/mysitecol") 
{ 
    List<SPWebInfo> websInfo = site.AllWebs.WebsInfo.FindAll(
        delegate(WebsInfo webInfo)
        {
            // filter to get us only the webs that start with our desired URL
            return webInfo.ServerRelativeUrl.StartsWith(webUrl);
        }
    );
    foreach(SPWebInfo webInfo in websInfo)
    {
         using(SPWeb web = site.OpenWeb(webInfo.Id))
         {

         }
    }
}


来源:https://stackoverflow.com/questions/36287458/how-to-loop-through-all-webs-and-sub-webs-of-a-sharepoint-web

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!