MOSS, Sharepoint Object Model and CAML: Recursive search (search in subfolders) in document libraries and lists

One of the nice features in SharePoint Object Model is querying lists and document libraries with CAML queries with GetItems method. One of the overloads of this method allows (a part of a) CAML query as parameter SPList.GetItem(SPQuery), meaning everything inside element – basically – you don’t pass the whole element, just it’s child.

You’ll notice that when you execute such a query, all items which would match the criteria, but are placed in the subfolders of the list/library, are not returned in the resulting SPListItemCollection.

The reason for this is simple: Element, which can contain element is the same level as element – it’s also a direct child of the element. So, because GetItems() method wants to see only element, we can’t pass the .

So, would it mean that GetItems() cannot search recursively? No. There is a way around – and it’s such a typical SharePoint way around 🙂

SPQuery object, which you pass as the parameter to the GetItems() method has a string property "ViewAttributes". This property contains already some default values and you have to check if one of them is already "Scope". Means, string parsing. If not, you can just add the following to the ViewAttributes property:

SPQuery.ViewAttributes += " Scope="Recursive"";

If the scope attribute is already present in ViewAttributes property, with some other value, you’ll have to change it to the Recursive. As I said, "ViewAttributes" is just a string so you won’t get around string parsing.

Happy coding 🙂