Retrieve all folders with sub-folders from SharePoint List
In this post, I’ll show you how to get all the folders including subfolders from Document Library or List in sharepoint.
This is just easy, by using SPQuery object and setting ViewAttributes property in it; we can retrieve only the folders from the SharePoint List, with a single condition. Now I’ll show you a code,
SPSite site = SPContext.Current.Site;
SPWeb web = SPContext.Current.Web;
SPList list = web.Lists["Shared Documents"];
SPQuery query = new SPQuery();
//Condition to check the item type is folder or not
query.Query = “<Where><Eq><FieldRef Name=’FSObjType’/><Value Type=’Lookup’>1</Value></Eq></Where>”;
//Get all the items including subfolders from the list query.ViewAttributes = “Scope=’RecursiveAll’”;
//Retrieve the items based on Query SPListItemCollection items = list.GetItems(query);
string folderDetails=“”;
//Get the name and Url for the folder
foreach (SPListItem item in items)
{
folderDetails += “Folder Name:” + item.Name + “<br/>Folder URL:” + web.Url + “/” + item.Url + “<br/>”;
}
In Query property of SPQuery object, we have to set the condition of “FSObjType” is equal to 0, this is the “Item Type” value for the folder, the list items or documents contain the Item Type value as 1.
And then Scope=’RecursiveAll’ is nothing but to retrieve all the items and folders from the list or library.
I’ll hope this post help you all about retrieving all the folders from the SharePoint List or Library.
- MOSS
- SharePoint
Filed Under
RSS feed for comments on this post. TrackBack URL

4 Comments »
Hi Shanta,
I am using this code however it gives error,even I have tried with default site also there is no output.
Please help me with this.
http://servername
SPSite site = new SPSite(”http://docholder:41653/”);
SPWebCollection collWebsites = site.AllWebs;
foreach (SPWeb oWebsite in collWebsites)
{
SPFolderCollection collFolders = oWebsite.Folders;
foreach (SPFolder oFolder in collFolders)
{
SPFileCollection collFiles = oFolder.Files;
long lngTotalFileSize = 0;
for (int intIndex = 0; intIndex < collFiles.Count; intIndex++)
{
lngTotalFileSize += collFiles[intIndex].Length;
}
Label1.Text += " Web: " +
oWebsite.Name
+ " Folder: " +
oFolder.Name + " Number: "
+ oFolder.Files.Count +
" Size: " + lngTotalFileSize + "”;
}
oWebsite.Dispose();
}
Comment by ravikiran — September 14, 2009 @ 12:30 pm
Nice Article. Helped me alot. Thanks.
Comment by Kishore — February 19, 2010 @ 7:14 am
Really Very Useful for beginners.Works fine.
Comment by Kishore — February 19, 2010 @ 7:15 am
faxless bad credit payday loan
payday loans fast
fax payday loan
fast cash payday loans
Comment by Gaskerr — July 20, 2010 @ 2:48 am