Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to ask Google Drive if a file exists by name with google drive api

If I just box Files.List in a try-catch block like I've seen in other answers (like this one), search by name and the file doesn't exist, I just catch an exception with File not found 404 error in the exception message.

I don't think the only way to know if a file exists or not is doing something like Contains("404") on a catched exception message... Is it?

I've searched on google and here, and I can't find anything apart from "use Files.List()".

Am I missing something here?

like image 628
Nox Avatar asked Oct 16 '25 03:10

Nox


1 Answers

  • You want to confirm whether the file is existing in Google Drive using the filename.

If my understanding is correct, how about this method?

When a file is searched by the filename, you can use search query q of the files.list method in Drive API. In your case, you can use q=name='fileName'. When the files.list method is requested using q=name='fileName', if the file with the filename of fileName was not found, the property of files of the response has the empty array like {"files": []}. By this, I confirm the existence of the file.

The endpoint and sample script are as follows.

Endpoint:

GET https://www.googleapis.com/drive/v3/files?q=name%3D'fileName'

Sample script:

FilesResource.ListRequest listRequest = service.Files.List();
listRequest.Q = "name='fileName'";
var files = listRequest.Execute();

Note:

  • If you don't want to search in the trash box, please add trashed=false to q like name='fileName' and trashed=false.

References:

  • Search for Files
  • Quickstart

If this was not what you want, I apologize.

like image 157
Tanaike Avatar answered Oct 17 '25 19:10

Tanaike