Wednesday, 6 July 2011

Get Data from all the folder of a library using SpQuery.ViewAttributes

In recent project we were having the documents in document library organized in different folder structure. We have to show the latest uploaded documents on the homepage using some business logic.

But the problem was, spquery was returning only root level documents.

After googling i found the solution from http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.spquery.viewattributes.aspx

Which says the spquery contains ViewAttributes  property and setting it to recursive will do the job.

   
    SPWeb objSpWeb = SPContext.Current.Web)

    SPList objSpList = objSpWeb.Lists["MyLibrary"];
    SPView objSpView = objSpList.Views["MyView"];

    SPQuery objSpQuery = new SPQuery(objSpView);
    objSpQuery.ViewAttributes = "Scope=\"Recursive\"";
    SPListItemCollection objItemColl =  objSpList.GetItems(oQuery);

    foreach (SPListItem objListItem in objItemColl)
    {
        // Perform the required task
    }