Pages

Wednesday, July 11, 2012

SharePoint 2010 - Retrieving Items and Folders Recursively

At times you may have to retrieve both folders and items from a document library or list. To search in a specific folder, you can set the “Folder” property of SPQuery object to your desired folder. You will also need to specify “Scope=’RecursiveAll’” in ViewAttributes property of SPQuery object in order to make this lookup recursive. If you want to differentiate between folders and items, you can do that by retrieving “ContentType” property of SPListeItem object. Please see the following code snippet for more information.

string sourceFolder = "<Specify Source Folder URL>";
SPFolder folder = SPContext.Current.Web.GetFolder(sourceFolder);
SPQuery query = new SPQuery();
query.Folder = folder;
query.Query = "";
query.ViewAttributes = "Scope='RecursiveAll'";
SPListItemCollection sourceCol = list.GetItems(query);
foreach (SPListItem item in sourceCol)
{
     //Only check for list items in the folder
     if (item["ContentType"].ToString() == "Folder")
     {
         System.Diagnostics.Debug.WriteLine(("Folder URL: " + item.Web.Url + "/" + item.Url));
 
     }
      else
     {
                                   //System.Diagnostics.Debug.WriteLine(("Item URL: " + item.Web.Url + "/" + item.Url));
     }

No comments:

Post a Comment