Include Items from Folders within your CAML Query Results

This week I am teaching an advanced SharePoint 2007 development course here in Brussels (next one is end of September). It's a lot of fun to go through all the material and I have invested a lot of energy in updating the lab material to provide an end-to-end scenario for the students to work out. All Feature-based of course; avoiding as much as possible to create stuff using the browser. Next week I'll teach the same course in Norway. It will be a busy week since I have more than 30 participants. And we already have a beer-drinking evening planned (of course J).

A student came with an interesting question regarding CAML queries: "If we execute a CAML query using SPQuery, can I have the items from subfolders included in the results returned?".

By default, only items out of the root folder are returned but there is a property you can set to get the results out of a folder (or all of them if you write a small loop).

SPSite site = new SPSite("http://moss.litwareinc.com/testsite");
if (site != null)
{
   SPWeb web = site.OpenWeb();
   foreach (SPList docLib in web.Lists)
   {
     if (docLib.Title == "Shared Documents")
     {
     foreach (SPFolder subFolder in  docLib.RootFolder.SubFolders)
     {
        SPQuery query = new SPQuery();
        query.Query = "<OrderBy><FieldRef Name='Title'/></OrderBy>";
       query.Folder = subFolder;
        System.Data.DataTable table = docLib.GetItems(query).GetDataTable();
     }
   }
 }
}

Thanks CAML girl for the suggestion J

Update: Michael Hofer has a good posting showing how to recursively get the items out of the folders using a CAML query.