How to search an item in specific folder in one drive?

放肆的年华 提交于 2020-02-23 07:06:10

问题


I am using Microsoft Graph to manipulate files in OneDrive. I need to search for a file in a specific folder, and if the file exists, delete that file.

I am using the following code to search file, it gives the search results for the whole drive.

var checkIfExists = this.graphClient
 .Me
 .Drive
 .Search(item["FileName"].ToString())
 .Request()
 .GetAsync()
 .Result;

I need to search file in specific folder only for example in duplicate folder only.


回答1:


You can scope the search to any path you like. For example, using the default Graph Explorer dataset, we can search for finance across the entire Drive using this query:

https://graph.microsoft.com/v1.0/me/drive/root/search(q='finance')?select=name,id,webUrl

If we would prefer to only search under a single subfolder (for example /CR-227 Project/), then we can use that Path as the starting point:

https://graph.microsoft.com/v1.0/me/drive/root:/CR-227 Project:/search(q='finance')?select=name,id,webUrl

Additionally, if we know the DriveItem.Id for /CR-227 Project/ (01BYE5RZ6TAJHXA5GMWZB2HDLD7SNEXFFU), then we could use that Id instead of the Path:

https://graph.microsoft.com/v1.0/me/drive/items/01BYE5RZ6TAJHXA5GMWZB2HDLD7SNEXFFU/search(q='finance')?select=name,id,webUrl



回答2:


As Drive is the top level resource that represents a user's one drive, it has relationships to other items that are known as DriveItems. A drive item can be anything, a file, folder, or any other item stored in the drive.

So, to search for a specific file inside the drive you could make a request;

var driveItems = await graphClient.Me.Drive.Root
.Search(<'{search-query}'>)
.Request()
.GetAsync();

This should help you get the DriveItem based on your search query, once you've retrieved the DriveItem, you can make a request for deleting it based on the id of the item;

await graphClient.Me.Drive
.Items[<"{item-id}">]
.Request()
.DeleteAsync();

Update:

As per the request for the help with the code for finding the file and deleting it, I've given it below for your reference.

var files = await graphClient.Me.Drive.Root
.Search("abc.pdf")
.Request()
.GetAsync();

var duplicateFile = files
.Where(driveItem => driveItem.ParentReference.Name
.ToLower() == "duplicate")
    .FirstOrDefault();

if(duplicateFile != null) {
await graphClient.Me.Drive
.Items[duplicateFile.Id]
.Request()
.DeleteAsync();
}


来源:https://stackoverflow.com/questions/56302835/how-to-search-an-item-in-specific-folder-in-one-drive

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!