Enumerate folders

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



The following code example is an excerpt from Programming Applications for Microsoft Office Outlook 2007.

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 =
        DefaultStore.GetRootFolder() as Outlook.Folder;

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

See also