SharePoint Stack Exchange is a question and answer site for SharePoint enthusiasts. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I am working with sandboxed solutons.(VS2010 C#) I need to retrieve all lists present in the site collection. I am able to get the lists from the site but not from entire sitecollection like subsites

 using (SPSite site = new SPSite(siteAddress))
                using (SPWeb web = site.OpenWeb())

                  //how can i get all lists from site and its sub sites?

share|improve this question
up vote 2 down vote accepted

You could try this:

foreach (SPWeb web in SPContext.Current.Site.AllWebs)
  foreach (SPList list in web.Lists)
    // Do work
share|improve this answer
Note that you'll not be able to use the returned list for anything without causing SharePoint to revitalize the disposed web, which then will leak. – Per Jakobsen Nov 4 '12 at 16:23
I didn't know that. So SPList got a reference to the original SPWeb object, which will revitalize when it is called upon – eirikb Nov 4 '12 at 18:54
Yes I see, it's a property ParentWeb on SPWeb which will be reopened (m_parentWeb in my dissasembler). Although it seems to do this when it is null only. @PerJakobsen you got a text-book solution for this? I see how one could wrap in using for each web, and then do work inside it, and even use Event as a callback. Feel free to edit the post :) – eirikb Nov 4 '12 at 19:07
It very much depends on the classes involved and what you need to do. But I usually prefer to do all the processing while looping through the webs (can be through a delegate). Sometimes it's better to keep the webs for which you return lists alive and dispose them in your own dispose method. – Per Jakobsen Nov 4 '12 at 21:04
@PerJakobsen, I have updated the answer with code I hope is safer. Although I love writing code like this: I believe this is more straight forward (and faster, for those that might care :) ). – eirikb Nov 4 '12 at 22:57

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.