Ram Prasad
 

Retrieve Items or Documents from a particular folder of a Sharepoint List or Document Library

Feb, 11 2013
 
1 min/s
 
 

Lists and Libraries are the commonly used data storage components is a Sharepoint portal. With data growing huge in the lists, site administrators usually create folders to make the data organized. We use the 'ViewAttribute' of the SPQuery object to fetch all the items from the folders and sub folders. Below is a sample code snippet

using (SPWeb spWeb = SPContext.Current.Site.AllWebs["Reports"])
{
    SPList spList = spWeb.Lists.TryGetList("ManageReports");
    SPQuery spQuery = new SPQuery();
    //Setting the ViewAttribute to "Scope='Recursive'" 
    //fetches all items from the list,
    //ie., also the items within the folders
    spQuery.ViewAttributes = "Scope=\"Recursive\"";
    SPListItemCollection items = spList.GetItems(spQuery);
}

If the 'ViewAttribute' is not specified for the SPQuery object, then only those items which are in the root folder (ie., the root level of the list) are returned. So, we need to specify the scope in ViewAttribute property to get the items from all the folders (if any) of a list.

GETTING ITEMS FROM A SPECIFIC FOLDER
In some scenarios we might need to fetch only the items within a sepcific folder. For this we can use the 'Folder' property of SPQuery class. Prepare the SPQuery object with the required CAML query, set the RowLimit and other required settings. And then set the 'Folder' property to a Folder object which represents the folder instance from where we need the items. Refer the below code snippet

using (SPWeb spWeb = SPContext.Current.Site.AllWebs["Reports"])
{
    SPList spList = spWeb.Lists.TryGetList("ManageReports");
    SPQuery spQuery = new SPQuery();
//Getting the folder object from the list 
SPFolder folder = spList.RootFolder.SubFolders["FolderName"];
//Set the Folder property
spQuery.Folder = folder;

SPListItemCollection items = spList.GetItems(spQuery);
//Now the items collection will have the items only from the given Folder

}