Find all subfolders of the Inbox folder using EWS

Sesame picture Sesame · Sep 29, 2011 · Viewed 20.3k times · Source

I have the following Inbox folder structure:

Inbox
--ABC
----ABC 2
----ABC 3
--XYZ
----XYZ 2
--123
----123 A
----123 B
----123 C

I am using Exchange Web Services and the following code to find the child folders of the Inbox folder:

ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2010);

service.AutodiscoverUrl("[email protected]");
Mailbox mb = new Mailbox("[email protected]");

FindFoldersResults findResults = service.FindFolders(
    WellKnownFolderName.Inbox,
    new FolderView(int.MaxValue));

foreach (Folder folder in findResults.Folders)
{
    Console.WriteLine(folder.DisplayName);
}

This partly works because it returns the ABC, XYZ, and 123 folders; unfortunately, it does not return the folders inside each of those folders (ABC 2, ABC 3, XYZ 2, 123 A, 123 B, 123 C).

Also, it is possible that a folder could have more than one level of subfolders inside it.

How can I write this code so that it will return all subfolders regardless of how deeply nested they may be?

Answer

Jakob Christensen picture Jakob Christensen · Sep 29, 2011

You can tell EWS to do a deep traversal when searching the folders. You can do this using the FolderView.Traversal property. Your code would then be changed to something similar to the following:

FindFoldersResults findResults = service.FindFolders(
    WellKnownFolderName.Inbox,
    new FolderView(int.MaxValue) { Traversal = FolderTraversal.Deep });