使用 OneDrive API 在另一个文件夹中创建一个文件夹

Creating a folder inside another folder with OneDrive API

我正在尝试使用 OneDrive API 在另一个文件夹中创建文件夹。我使用了 this 页中的文档。

首先我新建一个文件夹JSON对象:

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

其次,我将此对象添加到 HttpContent:

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

然后我提出这样的 post 请求:

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

这很好用,一个名为 New Folder 的文件夹被添加到我的云端硬盘的根目录中。现在我想在我刚刚创建的文件夹中创建一个文件夹。所以我提出了一个 post 请求,看起来像这样:

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

我希望在之前创建的文件夹中有一个名为 New Folder 的新文件夹。但是这个请求给我一个 Http 400 错误。

如何在另一个文件夹中创建新文件夹?

您的第二个请求格式不正确。

有两种方法可以将一个项目创建为另一个项目的子项 - 通过 ID 或通过路径。

按 id 看起来像:

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

按路径看起来像(注意冒号的使用):

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

鉴于上下文,您最有可能想要的是:

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

如果您使用的是 graphClient,则获取父文件夹的 ID 并将其传递给 items 方法,如下所示

folder = graphServiceClient.Me.Drive.Items[parentItem.Id].Children.Request().AddAsync(new DriveItem
            {
                Name = 'Name of the folder',
                Folder = new Folder()
            }).Result;