Tuesday, July 2, 2013

Obtain all files contained under folders and subfolders within a SharePoint Document Library

If you are looking for a way to programmatically return all documents of a specific content type located within a given SharePoint Document Library regardless of whether they are contained in folders and subfolders within the given library, I've provided the following sample method that will allow you to do just that:

private SPListItemCollection GetDocumentsByContentType(SPList docLibrary, string contentTypeName)
{
    SPQuery query = new SPQuery();
    query.ViewAttributes = "Scope=\"RecursiveAll\"";
    SPListItemCollection documents = null;
    try
    {
        query.Query = string.Format("<where><eq><fieldref name="ContentType"><value type="Text">{0}</value></fieldref></eq></where>", contentTypeName);
        documents = docLibrary.GetItems(query);
    }
    catch (Exception ex)
    {
        throw ex;
    }
    return documents;
}

The key to this code being able to return all documents, including documents contained under folders and subfolders, is that I've set the ViewAttributes property to be Scope="RecursiveAll".  Without this particular setting, the query would have only returned items that were located immediately under the SharePoint Document Library and would have skipped any documents contained under folders and subfolders.

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.