Take the 2-minute tour ×
SharePoint Stack Exchange is a question and answer site for SharePoint enthusiasts. It's 100% free, no registration required.

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

1 Answer 1

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
  }
  web.Dispose();
}
share|improve this answer
2  
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
1  
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
1  
@PerJakobsen, I have updated the answer with code I hope is safer. Although I love writing code like this: gist.github.com/a7c6efb2360382933896 I believe this is more straight forward (and faster, for those that might care :) ). –  eirikb Nov 4 '12 at 22:57

Your Answer

 
discard

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.