Search code examples
c#asp.net-coremicrosoft-graph-api

Using MS Graph API to create a new folder by path


I am not sure if this is even possible but if I were to know the path of some premade folders such as "Online Archive/Inbox/TestParentFolder/" and I wanted to create a new folder inside TestParentFolder.How would I go about doing this with ms graph api in c#? Also not sure if its important but these subfolders/path are in the Online Archive as indicated in the path above but from my research that is handled similar to any other folder.

I am able to create folders in the main directory using the following:

        public async Task<Models.Folder> CreateArchiveFolderAsync(string mailbox, string stateAbbreviation, string folderName)
    {
        var requestBody = new MailFolder
        {
            DisplayName = folderName,
            IsHidden = false,
        };

        // To initialize your graphClient, see https://learn.microsoft.com/en-us/graph/sdks/create-client?from=snippets&tabs=csharp
        var result = await _graphServiceClient!.Users[mailbox].MailFolders.PostAsync(requestBody);

        return new Models.Folder() {
            Id = result.Id
        };
    }

Solution

  • You can't get mailFolder by path. You need to go from the root mailFolder to the last subfolder in the path to get the mailFolder id.

    Then use it's id as the parentFolderId when creating a new folder inside it.

    Should be quite easy with Graph SDK v5.

    private async Task CreateMailSubfolder(GraphServiceClient graphServiceClient, string mailBox, string mailFolderPath, string mailFolderName)
    {
        // split mail folders
        var mailFolders = mailFolderPath.Split('/');
        var parentFolderId = string.Empty;
        foreach (var mailFolder in mailFolders)
        {
            // get root mail folder id
            if (string.IsNullOrEmpty(parentFolderId))
            {
                var folder = await graphServiceClient.Users[mailbox].MailFolders.GetAsync(rc =>
                {
                    rc.QueryParameters.Filter = $"displayName eq '{mailFolder}'";
                });
                parentFolderId = folder.Value[0].Id;
            }
            else
            {
                // get subfolder id
                var folder = await graphServiceClient.Users[mailbox].MailFolders[parentFolderId].ChildFolders.GetAsync(rc =>
                {
                    rc.QueryParameters.Filter = $"displayName eq '{mailFolder}'";
                });
                parentFolderId = folder.Value[0].Id;
            }
        }
    
        // create new subfolder
        var newMailFolder = await graphServiceClient.Users[mailbox].MailFolders[parentFolderId].ChildFolders.PostAsync(new MailFolder
        {
            ParentFolderId = parentFolderId,
            DisplayName = mailFolderName
        });
    }