1

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.

2

2 Answers 2

3

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\"";
2
  • 1
    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, 2013 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, 2014 at 9:12
1

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

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.