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.
Fetch the root and use
qry.ViewAttributes = "Scope='RecursiveAll'";
See also: Query to get all items in a list including items in the sub folders in SharePoint
And: http://www.ktskumar.com/blog/2009/07/retrieve-all-folders-from-list/
HTH Alex