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.
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
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();
}