How To Get all ITEMS from Folders and Sub-folders of PublicFolders Using EWS Managed API

user1891567 picture user1891567 · Dec 14, 2012 · Viewed 25.8k times · Source

How to retrieve all items from "public folders" and its "sub-folders" in exchange server2010 uisng managed API???

rootfolder = Folder.Bind(service,WellKnownFolderName.PublicFoldersRoot);
rootfolder.Load();                                             
foreach (Folder folder in rootfolder.FindFolders(new FolderView(int.MaxValue)))
{
FindItemsResults<Item> findResults = folder.FindItems(iv); 
 foreach (Item item in findResults)

         {
            //get item info;
         } 
}

"If i do like this i am not getting items present in sub-folders of it..public folders does not support deep traversal queries too..How can i get items from sub-folders of public folders???"

Answer

ono2012 picture ono2012 · Mar 7, 2013

To get all folders use the code below:

public void GetAllFolders(ExchangeService service, List<Folder> completeListOfFolderIds)
    {
        FolderView folderView = new FolderView(int.MaxValue);
        FindFoldersResults findFolderResults = service.FindFolders(WellKnownFolderName.PublicFoldersRoot, folderView);
        foreach (Folder folder in findFolderResults)
        {
            completeListOfFolderIds.Add(folder);
            FindAllSubFolders(service, folder.Id, completeListOfFolderIds);
        }
    }

private void FindAllSubFolders(ExchangeService service, FolderId parentFolderId, List<Folder> completeListOfFolderIds)
    {
        //search for sub folders
        FolderView folderView = new FolderView(int.MaxValue);
        FindFoldersResults foundFolders = service.FindFolders(parentFolderId, folderView);

        // Add the list to the growing complete list
        completeListOfFolderIds.AddRange(foundFolders);

        // Now recurse
        foreach (Folder folder in foundFolders)
        {
            FindAllSubFolders(service, folder.Id, completeListOfFolderIds);
        }
    }

To get all items:

List<Folder> completeListOfFolderIds = new List<Folder>();
//Fills list with all public folders and subfolders
GetAllFolders(service, completeListOfFolderIds);
foreach(Folder folder in completeListOfFolderIds)
{
ItemView itemView = new ItemView(int.MaxValue);
FindItemsResults<Item> searchResults = service.FindItems(folder.Id, itemView);
//do something with item list    
}

FYI FindFolders /FindItems only returns first 1000 items, so you'll have to alter this code to overcome that if you have massive structures.