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);
//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.