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 making a SharePoint 2010 visual web part, and I want to recursively iterate through all files in a document library which has nested folders. I can get a SPListItemCollection for all items and folders in the top level. As I iterate through the files, I can check if the current file is a item or folder. If its a folder, how can I get a SPListItemCollection object for everything in that folder? When I check the API, the closest method returns a SPFileCollection...


share|improve this question
Possible duplicate of… – Muhammad Raja May 10 '13 at 7:46
I fail to see that as a dupe. The linked question is different, even if the answer happens to contain some code that could fit this question. – SPArchaeologist May 10 '13 at 8:55

You can get items collection very simply. Try this code:

public static SPListItemCollection GetItemsRecursive(SPFolder folder)
    SPList list = folder.ParentWeb.Lists[folder.ParentListId];
    SPQuery query = new SPQuery();
    query.Folder = folder;                        //set folder for seaching;
    query.ViewAttributes = "Scope=\"Recursive\""; //set recursive mode for items seaching;
    return list.GetItems(query);

This code return only file items, folder items will missing. If you need get file items and folder items, set view attribute "Scope" to "RecursiveAll".

query.ViewAttributes = "Scope=\"RecursiveAll\"";
share|improve this answer
Can this code be changed to make it work for client object model? Because my Folder object does not have ParentWeb or ParentListId properties. – Aditi Dec 20 '13 at 6:24
So, you may get it values as method params. And what client object model you mean? (C#.NET / JavaScript) – shaman Jan 27 '14 at 9:12

From the SPList, grab the RootFolder property (

In the RootFolder (an SPFolder) use Files property to get the SPFileCollection in the folder (

Then on the RootFolder (and each subsequent subfolder), use the SubFolders property to iterate through each subfolder (

Something like:

var rootFolder = list.RootFolder;
foreach (SPFile file in rootFolder.Files)
// do something

foreach (SPFolder folder in rootFolder.SubFolders)
foreach (SPFile file in folder.Files)
// do something
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.