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


10

我正在使用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?

Answers:


4

Graph API提供了一种搜索工具,您可以利用它来查找是否存在某项。您可以选择先运行搜索然后在未找到任何内容的情况下创建一个项目,或者按照@ 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://docs.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
            }
        }

用于搜索项目的查询文本。值可以跨多个字段匹配,包括文件名,元数据和文件内容。

您可以使用搜索查询并做类似的事情filename=<yourName>或可能检查文件类型(我想这对您的特定情况没有帮助,但出于完整性考虑,我会提到它)


1

在容器上发出搜索请求

var existingItems = await graphServiceClient.Me.Drive
                          .Items["id-of-folder-I-am-putting-this-into"]
                          .Search("search")
                          .Request().GetAsync();

然后,您必须遍历existingItems集合(可能包括多个页面),以确定该项目是否存在。

您没有指定确定项目是否存在的标准。假设您的名字意思是,您可以:

var exists = existingItems.CurrentPage
               .Any(i => i.Name.Equals(Customer_Name.Text + Customer_LName.Text);

是的,但是我如何从中获取ID存在?
user979331 '19

使用Where()或FirstOrDefault()或适当的表达式。
Paul Schaeflein

1

要获得具有文件夹名称的文件夹:

调用图api Reference1 Reference2/me/drive/items/{item-id}:/path/to/file

/drive/items/id-of-folder-I-am-putting-this-into:/{folderName}

  • 如果该文件夹存在,则返回一个driveItem响应,该响应具有ID

  • 如果该文件夹不存在,则返回404(NotFound)

现在,在创建文件夹时,如果该文件夹已经存在,为了使呼叫失败,请尝试如下设置其他数据:参考

    AdditionalData = new Dictionary<string, object>
    {
        { "@microsoft.graph.conflictBehavior", "fail" }
    }
  • 如果该文件夹存在,则将返回409冲突

但是,如何获取现有文件夹的ID?
user979331 '19

1

一个基于查询的方法可能会在这方面加以考虑。由于设计DriveItem.name属性在文件夹中是唯一的,因此以下查询演示了如何driveItem按名称过滤以确定驱动器项是否存在:

https://graph.microsoft.com/v1.0/me/drive/items/{parent-item-id}/children?$filter=name eq '{folder-name}'

可以用C#表示如下:

var items = await graphClient
            .Me
            .Drive
            .Items[parentFolderId]
            .Children
            .Request()
            .Filter($"name eq '{folderName}'")
            .GetAsync();

给定提供的端点,流程可以包括以下步骤:

  • 提交请求以确定是否存在具有给定名称的文件夹
  • 如果找不到文件夹,请提交第二个文件夹(或返回现有文件夹)

这是一个更新的示例

//1.ensure drive item already exists (filtering by name) 
var items = await graphClient
            .Me
            .Drive
            .Items[parentFolderId]
            .Children
            .Request()
            .Filter($"name eq '{folderName}'")
            .GetAsync();



if (items.Count > 0) //found existing item (folder facet)
{
     Console.WriteLine(items[0].Id);  //<- gives an existing DriveItem Id (folder facet)  
}
else
{
     //2. create a folder facet
     var driveItem = new DriveItem
     {
         Name = folderName,
         Folder = new Folder
         {
         },
         AdditionalData = new Dictionary<string, object>()
         {
                    {"@microsoft.graph.conflictBehavior","rename"}
         }
     };

     var newFolder = await graphClient
                .Me
                .Drive
                .Items[parentFolderId]
                .Children
                .Request()
                .AddAsync(driveItem);

  }

-1

您可以通过调用以下命令获取文件夹的ID :https://graph.microsoft.com/v1.0/me/drive/root/children。它会为您提供驱动器中的所有项目。您可以使用名称或其他属性来过滤结果,以获取文件夹ID(如果尚未拥有)

public static bool isPropertyExist (dynamic d)
{
  try {
       string check = d.folder.childCount;
       return true;
  } catch {
       return false;
  }
}
var newFolder = await {https://graph.microsoft.com/v1.0/me/drive/items/{itemID}}


if (isPropertyExist(newFolder))
{
  //Your code goes here.
}

如果驱动器中的项目类型是文件夹,它将获得一个folder属性。您可以检查此属性是否存在,以及是否确实运行代码以添加该项目。

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.