i have a requirement to loop all document libraries from sharpeoint server, however i failed at subsite of the subsite
first of all i use method below to get my 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;
}
after that i use the return sitecollection url to loop for subsite as below code
using (SPSite site = new SPSite(SiteCollectionUrl))
{
foreach (SPWeb web in site.AllWebs)
{
//i get the subsite url from here
}
}
right now here is my problem, as i mentioned earlier, i wanted to get subsite of the subsite, so i pass my subsite url to SPSite, however it will only loop SiteCollections instead of my subsites
foreach (SPWeb web in site.AllWebs) <-- i means here, over here will only loop my sitecollection item alhought i already pass my subsite url as parameters
If you only want direct descendent subsites of a given site, you should use the SPWeb.Webs
property instead of the SPSite.AllWebs
property.
Gets a website collection object that represents all websites immediately beneath the website, excluding children of those websites.
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();
}
If you also need to get all the subsites of those subsites until all descendants (both direct and indirect) are accounted for, you should use recursion within the loop.
Note that instantiating and disposing of SPWeb objects for each subsite can be performance burden.
If you don't need to access the full properties of each subsite, you're better off using the site collection's AllWebs
property to get a reference to an SPWebCollection
object. You can then use the WebsInfo
property of that SPWebCollection
to get a List<>
of lightweight SPWebInfo objects, as mentioned in this answer.