detale
detale

Reputation: 12892

Microsoft Graph API client library - create a folder

I'm trying to create a folder under an existing folder in SharePoint using Microsoft Graph (C# SDK). I understand creating the folder on SharePoint or OneDrive should be the same when using the Graph API, but still, I couldn't find any good online references. The only article I found is an old one, which only has an example in JavaScript.

I have a root folder A and I want to create a subfolder B under A.

Here is the code:

var driveRequestBuilder = graphClient
    .Sites[SharePointSiteId]
    .Lists[ListId]
    .Drive;

var folderRequestBuilder = driveRequestBuilder
    .Root
    .ItemWithPath("A");
var folderDriveItem = folderRequestBuilder
    .Request()
    .GetAsync()
    .Result; // This returns the root folder "A"'s info

var subFolderDriveItem = new DriveItem()
{
    Name = "B",
    Folder = folderDriveItem.Folder
};
var result = folderRequestBuilder
    .Request()
    .CreateAsync(subFolderDriveItem)
    .Result;

The last line of code throws an AggregateException (because of TPL), which contains the inner exception:

Code: -1, Microsoft.SharePoint.Client.InvalidClientQueryException
Message: The parameter folder does not exist in method getByPath.
Inner error

I want to know the correct syntax to create the subfolder.

Upvotes: 2

Views: 4961

Answers (1)

Vadim Gremyachev
Vadim Gremyachev

Reputation: 59318

In case of sub folder the endpoint for creating a folder should be

POST https://graph.microsoft.com/v1.0/sites/{site-id}/lists/{list-id}/drive/root:/{path}:/children
Content-Type: application/json

{
  "name": "New folder name",
  "folder": { },
  "@microsoft.graph.conflictBehavior": "rename"
}

Example for msgraph-sdk-dotnet:

var folder = new DriveItem
{
    Name = "<sub folder name>",
    Folder = new Folder()
};

var result = await graphClient
    .Sites[siteId]
    .Lists[listId]
    .Drive
    .Root
    .ItemWithPath("<folder path>")
    .Children
    .Request()
    .AddAsync(folder);

Upvotes: 6

Related Questions