How to get all folder AND items from a sharepoint list?

LMW-HH picture LMW-HH · Oct 31, 2011 · Viewed 18.5k times · Source

I have a list containing folders and items. The folders are a specific content type based on folder, but with properties.

A folder can contain subfolders and subitems. A subfolder can contain sub-subfolders and so on. I already managed to get all items and folders using this way:

    void TraverseList(SPList list)
    {
        Trace.WriteLine("Traversing list: " + list.Title);
        Trace.WriteLine("Base type: " + list.BaseType.ToString());
        TraverseListFolder(list.RootFolder);
    }

    void TraverseListFolder(SPFolder folder)
    {
        SPQuery qry = new SPQuery();
        qry.Folder = folder;
        Trace.WriteLine("Foldername: " + folder.Name);
        SPWeb web = null;

        try
        {
            web = folder.ParentWeb;
            SPListItemCollection ic = web.Lists[folder.ParentListId].GetItems(qry);

            foreach (SPListItem subitem in ic)
            {
                SPFieldLookupValue temp = new SPFieldLookupValue(subitem["TargetPage"].ToString());
                Trace.WriteLine("TargetPage: " + temp);
                Trace.WriteLine("ItemName: " + subitem.Name);
                if (subitem.Folder != null)
                {
                    TraverseListFolder(subitem.Folder);
                }
            }
        }
        catch (Exception ex)
        {
            Trace.WriteLine(ex.Message);
            throw;
        }
        finally
        {
            if (web != null)
            {
                web.Dispose();
            }
        }
    }

The problem in this solution is that I have to send a new query for every folder, which is getting imperformant when the list is growing. Is there a way to get the whole list with one call, without loosing the folder/item structure?

Thank you for reading this!

Edit: It's not a requirement to use CAML. But there is a restriction I forgot: I'm not able to use webservices, due to customer restrictions.

Answer

Alex Duggleby picture Alex Duggleby · Oct 31, 2011