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've developed a console application for looping through all the webs inside my SharePoint 2010 site, but it's kind of slow, until the point that it throws OutOfMemory exception. This is the code I use (although that example is for a webpart...the way of iterating the site applies for a console application as well).

What I need to do is to loop through each web within a site, and then loop through each folder within each document library. This is because we're indexing all these data for another purposes.

Does anybody know about a better and faster way?

share|improve this question
What do you need inside each folder? File names/contents/whatever? – Andrey Markeev May 13 '11 at 5:40
Please paste in the specific code you use into the Question – Anders Rask May 13 '11 at 6:57
Are you disposing the objects after you extract the information you need? If you're hitting every web without disposing the previous one before then you're potentially looking at a pretty serious memory/resource hogging chunk of code, be it compiled or simply PowerShell. – webdes03 May 22 '11 at 23:14

I think you can use SPSiteDataQuery to enumerate all files in all document libraries of one SPSite. This will prevent folder recursion and raise the speed.

For example, you can query Guid for each item, and then enumerate all files using SPWeb.GetFile.

 SPSiteDataQuery query = new SPSiteDataQuery();

 // All document libraries
 query.Webs = "<Webs Scope=\"SiteCollection\" />";

 // All document libraries
 query.Lists = "<Lists BaseType=\"1\" />";

 query.ViewFields = "<FieldRef Name=\"UniqueId\" />";
 query.ViewFields += "<ProjectProperty Name=\"WebId\" />";

 DataTable dt = site.RootWeb.GetSiteData(query);

 foreach (DataRow row in dt.Rows)
     using (SPWeb web = site.OpenWeb(row["ProjectProperty.WebId"]))
         var file = web.GetFile(new Guid(row["UniqueId"].ToString()));

         // do whatever you need with this file


Actually, if you don't need file contents, you probably could query all the data using SPSiteDataQuery, without file enumeration. For example, to get file size, you should add to your ViewFields this string: "<FieldRef Name=\"" + SPBuiltInFieldId.FileSizeDisplay.ToString("B") + "\">".

MSDN references:

share|improve this answer

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.