Iterate through mailfolders using Microsoft Graph SDK (Client) in C#

SAC_535 36 Reputation points
2022-05-10T15:45:24.147+00:00

How to iterate or loop to list of folders of selected mail folder and work on it using graph client in C#

Use case 1:

GraphServiceClient graphClient = new GraphServiceClient( authProvider );

var mailFolder = await graphClient.Me.MailFolders["msgfolderroot"]
.Request()
.GetAsync();

Use case 2 :

GraphServiceClient graphClient = new GraphServiceClient( authProvider );

var mailFolder = await graphClient.Me.MailFolders[id]
.Request()
.GetAsync();

Microsoft Graph
Microsoft Graph
A Microsoft programmability model that exposes REST APIs and client libraries to access data on Microsoft 365 services.
11,320 questions
0 comments No comments
{count} votes

2 answers

Sort by: Most helpful
  1. Srinivasa Rao Darna 6,711 Reputation points Microsoft Vendor
    2022-05-10T18:43:30.957+00:00

    Hi @SAC_535 ,

    Refer to example list-childfolders, the code snippet should be able to get list of folders of selected mail folder.

    GraphServiceClient graphClient = new GraphServiceClient( authProvider );  
      
    var childFolders = await graphClient.Me.MailFolders["{mailFolder-id}"].ChildFolders  
    	.Request()  
    	.GetAsync();  
    

    Hope this helps,

    If the answer is helpful, please click "Accept Answer" and kindly upvote it. If you have further questions about this answer, please click "Comment".


  2. CarlZhao-MSFT 39,746 Reputation points
    2022-05-11T09:01:56.56+00:00

    Hi @SAC_535

    Please refer to my code, hope it helps you:

        GraphServiceClient graphClient = new GraphServiceClient( authProvider );  
    
        var mailFolders = await graphClient.Me.MailFolders  
            .Request()  
            .GetAsync();  
    
        for (int i = 0; i < mailFolders.Count; i++) {   
          
            var mailFolderId = mailFolders[i].Id.ToString();  
    
            var childFolders = await graphClient.Me.MailFolders[mailFolderId].ChildFolders.Request().GetAsync();  
    
            Console.WriteLine("childFolders:" + JsonConvert.SerializeObject(childFolders));  
        }  
    

    If the answer is helpful, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.