How to: Enumerate Folders

This example shows how to enumerate folders by iterating through a collection of folders.

Programming Applications for Office Outlook 2007

The following code example is an excerpt from Programming Applications for Microsoft Office Outlook 2007, from Microsoft Press (ISBN 9780735622494, copyright Microsoft Press 2007, all rights reserved).

Buy this book

Sample chapters

In the following code example, the EnumerateFoldersInDefaultStore method first obtains the root folder for the default store by using the GetRootFolder() method. It then calls the EnumerateFolders method on the root folder. EnumerateFolders takes in a root folder and walks through the folders of the default store that the root folder represents. EnumerateFolders first uses the Folders property to obtain the subfolders of the root Folder object. EnumerateFolders is then called recursively to enumerate all the folders in a hierarchy. Finally, EnumerateFolders writes the FolderPath property of each Folder to the trace listeners in the Listeners collection.

If you use Visual Studio to test this code example, you must first add a reference to the Microsoft Outlook 15.0 Object Library component and specify the Outlook variable when you import the Microsoft.Office.Interop.Outlook namespace. The using statement must not occur directly before the functions in the code example but must be added before the public Class declaration. The following line of code shows how to do the import and assignment in C#.

using Outlook = Microsoft.Office.Interop.Outlook;
private void EnumerateFoldersInDefaultStore()
{
    Outlook.Folder root =
        Application.Session.
        DefaultStore.GetRootFolder() as Outlook.Folder;
    EnumerateFolders(root);
}

// Uses recursion to enumerate Outlook subfolders.
private void EnumerateFolders(Outlook.Folder folder)
{
    Outlook.Folders childFolders =
        folder.Folders;
    if (childFolders.Count > 0)
    {
        foreach (Outlook.Folder childFolder in childFolders)
        {
            // Write the folder path.
            Debug.WriteLine(childFolder.FolderPath);
            // Call EnumerateFolders using childFolder.
            EnumerateFolders(childFolder);
        }
    }
}               

Other resources

Show:
© 2014 Microsoft