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

asp.netcsharepointsharepoint-2010sharepoint-2013

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

Best Answer

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

         }
    }
}