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 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...

Thanks.

share|improve this question
    
Possible duplicate of sharepoint.stackexchange.com/questions/67272/… –  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

2 Answers 2

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 at 9:12

From the SPList, grab the RootFolder property (http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.splist.rootfolder.aspx).

In the RootFolder (an SPFolder) use Files property to get the SPFileCollection in the folder (http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.spfolder.files.aspx).

Then on the RootFolder (and each subsequent subfolder), use the SubFolders property to iterate through each subfolder (http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.spfolder.subfolders.aspx).

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

 
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.