Get SPWeb at all the levels
-
28-09-2020 - |
Question
I have a root site with sites at different levels(depth is unknown). How can I find all the SPWeb objects iterating till the deepest level.
will the below code give me desired result
SPWebApplication mySPWebApp = SPWebApplication.Lookup(new Uri("http://test-site"));
{
foreach (SPSite siteCollection in mySPWebApp.Sites)
{
foreach (SPWeb oweb in siteCollection.AllWebs)
{
//My Code
}
}
}
Solution
Yes, with SPWebApplication.Sites you get all site collections in a web application and with SPSite.AllWebs you get all sites in a site collection no matter the level.
Best practice is to dispose explicitly of individual Web sites that are retrieved from the collection that is returned through the AllWebs property.
foreach (SPWeb oweb in siteCollection.AllWebs)
{
try
{
//Your code
}
finally
{
oweb.Dispose();
}
}
You should dispose site collections too.
OTHER TIPS
To build on @naim's answer, you should dispose both the Site Collections and the webs and use try/catch around the dispose or using statements.
Site Collection Dispose Example
from Best Practices: Using Disposable Windows SharePoint Services Objects
void SPSiteCollectionForEachNoLeak()
{
using (SPSite siteCollectionOuter = new SPSite("http://moss"))
{
SPWebApplication webApp = siteCollectionOuter.WebApplication;
SPSiteCollection siteCollections = webApp.Sites;
foreach (SPSite siteCollectionInner in siteCollections)
{
try
{
// ...
}
finally
{
if(siteCollectionInner != null)
siteCollectionInner.Dispose();
}
}
} // SPSite object siteCollectionOuter.Dispose() automatically called.
}
Web Dispose Example
from Best Practices: Using Disposable Windows SharePoint Services Objects
void SPWebCollectionAddNoLeak(string strWebUrl)
{
using (SPSite siteCollection = new SPSite("http://moss"))
{
using (SPWeb outerWeb = siteCollection.OpenWeb())
{
SPWebCollection webCollection = siteCollection.AllWebs; // No AllWebs leak just getting reference.
using (SPWeb innerWeb = webCollection.Add(strWebUrl))
{
//...
}
} // SPWeb object outerWeb.Dispose() automatically called.
} // SPSite object siteCollection.Dispose() automatically called.
}