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

Comments (11)

  1. MOhamad says:

    Hi

    what is the refference for ExchangeBinding?

    10x

    Moe

  2. MOhamad says:

    i need the refference for ExchangeBinding

  3. Vikas - MSFT says:

    My bad… I am using the following class with static functions to implement singleton pattern. You could also replace ExchangeBinding.CurrentInstance with ExchangeServiceBinding object.

    following is the class that I prefer to use

    using System;

    using System.Collections.Generic;

    using System.Text;

    using EWS_Explorer.EWS_Proxy;

    namespace EWS_Explorer.Wrappers

    {

       class ExchangeBinding

       {

           ExchangeBinding _ExchangeBinding;

           private static ExchangeServiceBinding _CurrentInstance;

           private static bool _ExchangeImpersonationEnabled;

           private static ImpersonationType _ImpType;

           private static string _ImpersonationString;

           public enum ImpersonationType

           {

               PrincipalName,

               SID,

               PrimarySMTP

           }

           public static ExchangeServiceBinding CurrentInstance

           {

               get {

                   if (null != _CurrentInstance)

                   {

                       if (_ExchangeImpersonationEnabled == true)

                       {

                           if(null==_CurrentInstance.ExchangeImpersonation)

                               _CurrentInstance.ExchangeImpersonation = new ExchangeImpersonationType();

                           if(null == _CurrentInstance.ExchangeImpersonation.ConnectingSID )

                               _CurrentInstance.ExchangeImpersonation.ConnectingSID = new ConnectingSIDType();

                           switch (_ImpType)

                           {

                               case ImpersonationType.PrincipalName:

                                   _CurrentInstance.ExchangeImpersonation.ConnectingSID.PrincipalName= _ImpersonationString;        

                                   break;

                               case ImpersonationType.SID:

                                   _CurrentInstance.ExchangeImpersonation.ConnectingSID.SID= _ImpersonationString;

                                   break;

                               case ImpersonationType.PrimarySMTP:

                                   _CurrentInstance.ExchangeImpersonation.ConnectingSID.PrimarySmtpAddress = _ImpersonationString;

                                   break;

                           }

                       }

                   }

                   return _CurrentInstance;

               }

               set { _CurrentInstance = value; }

           }

           public static string ImpersonateValue

           {

               get { return _ImpersonationString; }

               set { _ImpersonationString = value; }

           }

           public static ImpersonationType ImpersonateUsing

           {

               get { return _ImpType; }

               set { _ImpType = value; }

           }

           public static bool ExchangeImpersonationEnabled

       {

       get { return _ExchangeImpersonationEnabled;}

       set { _ExchangeImpersonationEnabled = value;}

       }

           private ExchangeBinding()

           {

               if (null == _ExchangeBinding)

                   _ExchangeBinding = new ExchangeBinding();

           }

       }

    }

  4. Damo says:

    Hi! Thanks for your post! I’m having trouble with passing in the root Public Folders Id to the function:

    When I debug I get the error message from the ‘ffrt.ResponseMessages.Items(0)’:

    “Id is malformed.”

    (sorry, I’ve converted it to VB)

    Here is the line in question…

    >>

    Dim ffrt As FindFolderResponseType = esb.FindFolder(fft)

    Dim rmt As ResponseMessageType = DirectCast(ffrt.ResponseMessages.Items(0), ResponseMessageType)

    <<

    Here is how I am currently calling the function:

    >>

    Dim publicFoldersRootId As New DistinguishedFolderIdType()

    publicFoldersRootId.Id = DistinguishedFolderIdNameType.publicfoldersroot

    ‘Print All Public Folders

    For Each folder As FolderType In FindAllFolder(publicFoldersRootId.Id)

           Console.WriteLine(folder.DisplayName)

    Next

    <<

    Any idea what I am doing wrong?

  5. Vikas - MSFT says:

    I guess you are passing wrong type of ID, can’t be sure unless I have your implementation of the function. I am using the below code to get the distinguished folder. See if that helps you.

    ”’ <summary>

    ”’ GetDistinguishedFolder

    ”’ <param name="FolderID"/>

    ”’ <example>GetDistinguishedFolder(DistinguishedFolderIdNameType.root)</example>

    ”’ </summary>

    ”’ <returns>BaseFolderType</returns>

    Public Shared Function GetDistinguishedFolder(ByVal FolderID As DistinguishedFolderIdNameType) As BaseFolderType

        If ExchangeBinding.CurrentInstance Is Nothing Then

            Return Nothing

        End If

       

        Dim dfit As DistinguishedFolderIdType() = New DistinguishedFolderIdType(0) {}

       

        ‘get the root folder ID

        dfit(0) = New DistinguishedFolderIdType()

        dfit(0).Id = FolderID

       

        ‘set the props that we want to retrieve

        Dim frst As New FolderResponseShapeType()

        frst.BaseShape = DefaultShapeNamesType.AllProperties

        ‘get the folder

        Dim gftRoot As New GetFolderType()

        gftRoot.FolderIds = dfit

       

        gftRoot.FolderShape = frst

        Dim gfrt As GetFolderResponseType = ExchangeBinding.CurrentInstance.GetFolder(gftRoot)

        Dim firmt As FolderInfoResponseMessageType = DirectCast(gfrt.ResponseMessages.Items(0), FolderInfoResponseMessageType)

        If firmt.ResponseClass = ResponseClassType.Success Then

            Return DirectCast(gfrt.ResponseMessages.Items(0), FolderInfoResponseMessageType).Folders(0)

        Else

            Return Nothing

        End If

    End Function

  6. Damo says:

    Bingo! I think I worked out what I was doing wrong.

    I think I was getting the folder ID mixed up with the DistinguishedFolderIdNameType.

    Additionally to Print to the Console a complete Public Folder list I made the following function using the GetDistinguishedFolder function and FindAllFolder function you supplied above:

       Public Sub PrintPublicFolders(ByRef esb As ExchangeServiceBinding, ByVal p_basefolder As BaseFolderType, Optional ByVal p_level As Integer = 0)

           If p_level = 0 Then Console.WriteLine(p_basefolder.DisplayName)

           ‘Print All Public Folders

           For Each folder As FolderType In FindAllFolder(esb, p_basefolder.FolderId.Id)

               For i As Integer = 0 To p_level

                   Console.Write("-")

               Next

               Console.WriteLine(folder.DisplayName)

               PrintPublicFolders(esb, folder, p_level + 1)

           Next

       End Sub

    To call the function I used:

               ‘Print All Public Folders

               Dim publicFolderBase As BaseFolderType = GetDistinguishedFolder(esb, DistinguishedFolderIdNameType.publicfoldersroot)

               PrintPublicFolders(esb, publicFolderBase)

  7. I’ve put together a list of articles which cover common questions on Exchange Web Services (EWS). These

  8. Banyan says:

    Here is my version that I cobbled together from your example and the comments. I don’t understand all of it but it seems to be working!  Thanks so much for publishing your example.

    BTW, if you see anything egregious in my code I’d appreciate it if you’d let me know.

    protected void btnTest_Click(object sender, EventArgs e)

           {    

               ExchangeServiceBinding esb = new ExchangeServiceBinding();

               esb.Url = "http://exch1.blahdeblah.org/EWS/Exchange.asmx&quot;;

               esb.RequestServerVersionValue = new RequestServerVersion();

               esb.RequestServerVersionValue.Version = ExchangeVersionType.Exchange2007_SP1;

               esb.Credentials = new NetworkCredential("englebert@blahdeblah.org", "password");

               BaseFolderType rootFolder = RootFolder(esb);

               PrintPublicFolders(esb, rootFolder, 0);                                            

           }

           private void PrintPublicFolders(ExchangeServiceBinding esb, BaseFolderType passedBaseFolder, int level)

           {

               if (level == 0) Response.Write(passedBaseFolder.DisplayName+"<br/>");

               BaseFolderType[] BaseFolderArray = FindAllFolders(esb,passedBaseFolder.FolderId.Id);

               foreach (BaseFolderType baseFolder in BaseFolderArray)

               {

                  for (int i = 0; i<level; i++)

                  {

                      Response.Write("—");

                  }

                   Response.Write(baseFolder.DisplayName+"<br/>");

                   PrintPublicFolders(esb,baseFolder,level + 1);

               }

           }

           static private BaseFolderType RootFolder(ExchangeServiceBinding esb)

           {

               DistinguishedFolderIdType[] fit = new DistinguishedFolderIdType[1];

               fit[0] = new DistinguishedFolderIdType();

               fit[0].Id = DistinguishedFolderIdNameType.publicfoldersroot;

               FolderResponseShapeType frst = new FolderResponseShapeType();

               frst.BaseShape = DefaultShapeNamesType.AllProperties;

               FindFolderType fft = new FindFolderType();

               fft.Traversal = FolderQueryTraversalType.Shallow;

               fft.ParentFolderIds = fit;

               fft.FolderShape = frst;

               FindFolderResponseType ffrt = esb.FindFolder(fft);

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

               if (rmt.ResponseClass != ResponseClassType.Success) throw new Exception("Root folder request failed. ResponseClass = " + rmt.ResponseClass.ToString());

               BaseFolderType[] bft = ((FindFolderResponseMessageType)ffrt.ResponseMessages.Items[0]).RootFolder.Folders;

               return bft[0];

           }

           static private BaseFolderType[] FindAllFolders(ExchangeServiceBinding esb, string parentFolderId)

           {

               if (esb == null) return null;

               if (parentFolderId == null) return null;

               FolderIdType[] fit = new FolderIdType[1];

               fit[0] = new FolderIdType();

               fit[0].Id = parentFolderId;

               FolderResponseShapeType frst = new FolderResponseShapeType();

               frst.BaseShape = DefaultShapeNamesType.AllProperties;        

               FindFolderType fft = new FindFolderType();

               fft.Traversal = FolderQueryTraversalType.Shallow;

               fft.ParentFolderIds = fit;

               fft.FolderShape = frst;

               FindFolderResponseType ffrt = esb.FindFolder(fft);

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

               if (rmt.ResponseClass != ResponseClassType.Success) return null;            

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

           }

  9. Jeremy says:

    private ExchangeBinding()

          {

              if (null == _ExchangeBinding)

                  _ExchangeBinding = new ExchangeBinding();

          }

    ???? Method Must have return Type…

  10. Vikas - MSFT says:

    That is a Class Constructor and not a method.

Skip to main content