gpt4 book ai didi

c# - 检查 Graph API 文件夹是否存在

转载 作者:行者123 更新时间:2023-11-30 18:45:21 24 4
gpt4 key购买 nike

我正在使用 Microsoft Graph API,我正在创建一个文件夹,如下所示:

var driveItem = new DriveItem
{
Name = Customer_Name.Text + Customer_LName.Text,
Folder = new Folder
{
},
AdditionalData = new Dictionary<string, object>()
{
{"@microsoft.graph.conflictBehavior","rename"}
}
};

var newFolder = await App.GraphClient
.Me
.Drive
.Items["id-of-folder-I-am-putting-this-into"]
.Children
.Request()
.AddAsync(driveItem);

我的问题是如何检查此文件夹是否存在以及它是否获取文件夹的 ID?

最佳答案

Graph API 提供了一个 search facility ,您可以利用它来查明某个项目是否存在。您可以选择先运行搜索,然后在未找到任何内容的情况下创建一个项目,或者您可以按照 @Matt.G 的建议并尝试 nameAlreadyExists异常:

        var driveItem = new DriveItem
{
Name = Customer_Name.Text + Customer_LName.Text,
Folder = new Folder
{
},
AdditionalData = new Dictionary<string, object>()
{
{"@microsoft.graph.conflictBehavior","fail"}
}
};

try
{
driveItem = await graphserviceClient
.Me
.Drive.Root.Children
.Items["id-of-folder-I-am-putting-this-into"]
.Children
.Request()
.AddAsync(driveItem);
}
catch (ServiceException exception)
{
if (exception.StatusCode == HttpStatusCode.Conflict && exception.Error.Code == "nameAlreadyExists")
{
var newFolder = await graphserviceClient
.Me
.Drive.Root.Children
.Items["id-of-folder-I-am-putting-this-into"]
.Search(driveItem.Name) // the API lets us run searches https://learn.microsoft.com/en-us/graph/api/driveitem-search?view=graph-rest-1.0&tabs=csharp
.Request()
.GetAsync();
// since the search is likely to return more results we should filter it further
driveItem = newFolder.FirstOrDefault(f => f.Folder != null && f.Name == driveItem.Name); // Just to ensure we're finding a folder, not a file with this name
Console.WriteLine(driveItem?.Id); // your ID here
}
else
{
Console.WriteLine("Other ServiceException");
throw;// handle this
}
}

The query text used to search for items. Values may be matched across several fields including filename, metadata, and file content.

你可以玩with search query并做类似 filename=<yourName> 的事情或可能检查文件类型(我想这对您的特定情况没有帮助,但为了完整起见我会提到它)

关于c# - 检查 Graph API 文件夹是否存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59160551/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com