Using the Microsoft Outlook 14.0 Object Library reference and the code below I would like to count all folders listed under the mailbox including every subfolder but I have a problem.

This code only counts the top level folders and second level folder but doesn’t count any subfolders beneath. Something wrong within my foreach statement in the countRootFolders method but I can’t work it out. Can anyone help?
Microsoft.Office.Interop.Outlook.Application app = null;
Microsoft.Office.Interop.Outlook._NameSpace ns = null;
private void button1_Click(object sender, EventArgs e)
{
app = new Microsoft.Office.Interop.Outlook.Application();
ns = app.GetNamespace("MAPI");
MessageBox.Show(countRootFolders().ToString());
}
public int countRootFolders()
{
Microsoft.Office.Interop.Outlook.MAPIFolder rootFolder = this.ns.Session.DefaultStore.GetRootFolder();
int rootCount = rootFolder.Folders.Count;
foreach (Microsoft.Office.Interop.Outlook.MAPIFolder subfolder in rootFolder.Folders)
{
rootCount += subfolder.Folders.Count;
}
return rootCount;
}
Any help greatly appreicated!!
It looks to me like your loop only asks each of the first level folders how many folders they have. So you get the number of folders in the root, and the number of folders each of those have one level down, but it doesn’t traverse the folder tree to ask further levels how many they have.
This is a simple tree traversal problem.
You’ll have to implement a recursive function to traverse down the folder structure to get an accurate count.
Call that with the root folder you want to count, and it should be pretty close to what you’re after.