Search code examples
c#restonedrive

Creating a folder inside another folder with OneDrive API


Im trying to create folder inside another folder using the OneDrive API. I used the documentation from this page.

First I create a new folder JSON object:

var folderObject = JObject.FromObject(new
{
    name = "New Folder",
    folder = new
    { }
});

Second I add this object to the HttpContent:

HttpContent content = new StringContent(folderObject.ToString(), Encoding.UTF8, "application/json");

Then I make a post request like this:

HttpResponseMessage response = await client.PostAsync("/v1.0/drive/root/children", content);

This works fine and a folder named New Folder is added to the root of my Drive. Now I want to create a folder inside the folder I just created. So I make a post request that looks like this:

HttpResponseMessage response = await client.PostAsync("/v1.0/drive/root/New Folder/children", content);

I expect a new folder named New Folder inside the previously created folder. But this request gives me a Http 400 error.

How can I create a new folder inside another folder?


Solution

  • Your second request is malformed.

    There are two ways to create an item as a child of another - by id or by path.

    By id would look something like:

    HttpResponseMessage response = await client.PostAsync("/v1.0/drive/root/items/{parentItem.id}/children", content);
    

    By path would look something like (note the use of colons):

    HttpResponseMessage response = await client.PostAsync("/v1.0/drive/root{parentItem path}:/children", content);
    

    Given the context, what you're after is most likely:

    HttpResponseMessage response = await client.PostAsync("/v1.0/drive/root:/New Folder:/children", content);