1

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?
                }

            }

1 Answer 1

2

You could try this:

foreach (SPWeb web in SPContext.Current.Site.AllWebs)
{
  foreach (SPList list in web.Lists)
  {
    // Do work
  }
  web.Dispose();
}
5
  • 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. Commented Nov 4, 2012 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
    Commented Nov 4, 2012 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
    Commented Nov 4, 2012 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. Commented Nov 4, 2012 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
    Commented Nov 4, 2012 at 22:57

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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