HOWTO: EWS: Find all folders inside a parent folder, helpful in generating a folder tree

Looks cool isn’t it? I have created this folder tree for my mailbox using Exchange Web Services. You can do the very same.

Here is the code which I am using to get all the folders inside a folder and recursively go deep-n-deep until your reach the core.

Here is the sample code…

       

/// <summary>

/// FindAllFolder: you need to pass the parent folder id to get all the child folders inside it.

/// NOTE: It returns only one level of child folders and

/// to get children inside a child folder you need to run it again recursively

/// </summary>

/// <param name="strParentFolderId">Id of the folder you want to enumerate for children</param>

/// <returns>BaseFolderType array containing all the child folders</returns>

static public BaseFolderType[] FindAllFolder(string strParentFolderId)

{

if (null == ExchangeBinding.CurrentInstance || null == strParentFolderId)

      return null;

//get the root folder ID

      FolderIdType[] fit = new FolderIdType[1];

      fit[0] = new FolderIdType();

      fit[0].Id = strParentFolderId;

     

//set the props that we want to retrieve

      FolderResponseShapeType frst = new FolderResponseShapeType();

      frst.BaseShape = DefaultShapeNamesType.AllProperties;

           

      //find the folder

      FindFolderType fft = new FindFolderType();

      fft.Traversal = FolderQueryTraversalType.Shallow;

      fft.ParentFolderIds = fit;

      fft.FolderShape = frst;

           

FindFolderResponseType ffrt = ExchangeBinding.CurrentInstance.FindFolder(fft);

      ResponseMessageType rmt = ((ResponseMessageType)ffrt.ResponseMessages.Items[0]);

if (rmt.ResponseClass == ResponseClassType.Success)

return ((FindFolderResponseMessageType)ffrt.ResponseMessages.Items [0]).RootFolder.Folders;

else

      return null;

}

 

 Keywords: FindFolder, Folder Enumeration, Exchange Web Services, Exchange 2007