Search files with Google Drive api v3


Please Share

The List files method.

Listing all of the files in a users Google Drive account can be a bit cumbersome with the Google Drive API V3. If a
user has a large number of files, and the limitations of only 1000 rows page page, this can lead to a lot of pagination on the part of your application in order to find the files you are looking for. In this tutorial I thought we would look at how to search for files with the Google Drive API using the Q parameter in the files.list method.

Google Drive API V3

Google Drive API V3

Using the Q parameter we can search on things like file type, file name, the directory that the file resides in, and a number of other things.

A query for filtering the file results. See the “Search for files” guide for the supported syntax

Authorization with private data

In order to access a users private data we will need the users permission, in order to get that permission we use Googles authorization server. To use the authorization server we must register our application on Google Developer console and create for this example I will be creating an installed application so I will be creating a .net core console application.

If you don’t know how to create an installed application on Google developer console i have a video which will walk you through it

How to create Google Oauth2 installed application

You may also find Google Developer Console Oauth2 credentials helpful in understanding how Oauth2 works.

Remember to enable the Google Drive API under library.

Add the Google Drive API V3 Nuget Package

In order to access the Google Drive API v3 we will need to add a nuget package Google.apis.drive.v3, which will give us access to all the methods we need in order to access the Google Drive api V3.

The Google Drive API v3 is a free api that returns file storage information about a users Google Drive account and the files they have stored there.

Constants

The first thing we will need to do is configure the client. I downloaded the installed client credentials for my project on Google Developer console. I have added a constant here which points to the path where the file exists. It’s a good idea to place this file in a save storage location.


private const string PathToCredentials = @"C:\Youtube\dev\credentials.json";

Configure authorization

Now we need to configure GoogleWebAuthorizationBroker. The thing you need to remember about GoogleWebAuthorizationBroker is this is ONLY for installed applications this code will not work if you use it in a web application because it will open the browser window on the machine the code is running on. In the case of a web server it needs to open the web browser on the users machine not the web server.

The second thing you need to understand about GoogleWebAuthorizationBroker is fileDatastore. FileDataStore is used to store the user credentials, by default it is installed in %appData% directory on windows. you can change this telling file datastore exactly where to store the user credentials.


// Credential storage location 
var tokenStorage = new FileDataStore("UserCredentialStoragePath", true);

 UserCredential credential;
            await using (var stream = new FileStream(PathToCredentials, FileMode.Open, FileAccess.Read))
            {
                // Requesting Authentication or loading previously stored authentication for userName
                credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
                        GoogleClientSecrets.Load(stream).Secrets,
                        new[] {DriveService.ScopeConstants.DriveReadonly},
                        "userName",
                        CancellationToken.None,
                        tokenStorage)
                    .Result;
            }

GoogleWebAuthorizationBroker requires that we pass it the path to the credentials file that we downloaded from google developer console (PathToCredentials). We can also configure the user which is used to store / load the credentials in FileDataStore, if you want to denote different users on a multi user system you would change “userName” depending upon whose credentials you would like to load.

Create Google drive service

Then all we need to do is create a DriveService. All requests to the API will then be run through the drive service object.


// Create the  Drive service.
var service = new DriveService(new BaseClientService.Initializer()
    {
     HttpClientInitializer = credential
     });

Google Drive API V3 Basic File.List method

The simple default use of the file.lists method is as follows. This will just list the first 100 files it find on the users Google drive account in no particular order that I have ever found.


var request = service.Files.List();
var results = await request.ExecuteAsync();

foreach (var driveFile in results.Files)
      {
       Console.WriteLine($"{driveFile.Name}  {driveFile.MimeType}  {driveFile.Id}");
       }

In my case the results are as follows

image.jpg image/jpeg 19yq0d7Lv53jorLP_iv00GZzirk1XhROS
test application/vnd.google-apps.folder 10krlloIS2i_2u_ewkdv3_1NqcpmWSL1w
StandardYouTubeThumb.png image/png 1gq0cmDEkoac9sCjlxcCgOIncs5L4Br3F
Untitled document application/vnd.google-apps.document 1v8QrAOxyC_5LQNovaq9XNALvnDocKeF6HxrrHPyWwRU

Lets make some changes to it.

Add Page size to files.list

Now let’s test out the files.list method. I can pass it an optional parameter of PageSize which will tell the api to return to me 1000 rows, the default is 100.


var request = service.Files.List();
request.PageSize = 1000;
var results = await request.ExecuteAsync();

foreach (var driveFile in results.Files)
      {
       Console.WriteLine($"{driveFile.Name}  {driveFile.MimeType}  {driveFile.Id}");
       }

In my case the results have not changed as I am using a test Google drive account which does not actually have that many files uploaded to it yet.

image.jpg image/jpeg 19yq0d7Lv53jorLP_iv00GZzirk1XhROS
test application/vnd.google-apps.folder 10krlloIS2i_2u_ewkdv3_1NqcpmWSL1w
StandardYouTubeThumb.png image/png 1gq0cmDEkoac9sCjlxcCgOIncs5L4Br3F
Untitled document application/vnd.google-apps.document 1v8QrAOxyC_5LQNovaq9XNALvnDocKeF6HxrrHPyWwRU

Search for folders

If you check the response i am getting back the mime type is application/vnd.google-apps.folder this is the mime type for a folder on Google Drive. So what if we just want to see folders on Google Drive. Here is where we can use the Q parameter and search for just folders


var request = service.Files.List();
request.PageSize = 1000;
request.Q = mimeType in 'application/vnd.google-apps.folder'
var results = await request.ExecuteAsync();

foreach (var driveFile in results.Files)
      {
       Console.WriteLine($"{driveFile.Name}  {driveFile.MimeType}  {driveFile.Id}");
       }

Notice how I passed the mimeType of ‘application/vnd.google-apps.folder’. Now I am only getting the single result back, because I only have one folder on my Google drive account.

test application/vnd.google-apps.folder 10krlloIS2i_2u_ewkdv3_1NqcpmWSL1w

Search for files with in a folder

Ok what if I just wanted to see files in a folder. Well then we could search on the parent parameter.


var request = service.Files.List();
request.PageSize = 1000;
request.Q = "parents in '10krlloIS2i_2u_ewkdv3_1NqcpmWSL1w'";
var results = await request.ExecuteAsync();

foreach (var driveFile in results.Files)
      {
       Console.WriteLine($"{driveFile.Name}  {driveFile.MimeType}  {driveFile.Id}");
       }

Notice how I passed the file id of the folder in ”s. Now we are getting back all the files which are in the folder.

image.jpg image/jpeg 19yq0d7Lv53jorLP_iv00GZzirk1XhROS
StandardYouTubeThumb.png image/png 1gq0cmDEkoac9sCjlxcCgOIncs5L4Br3F
Untitled document application/vnd.google-apps.document 1v8QrAOxyC_5LQNovaq9XNALvnDocKeF6HxrrHPyWwRU

Search for only documents within a folder

Ok what if I wanted to see only the document in the folder. Well you can add more then one search string


var request = service.Files.List();
request.PageSize = 1000;
request.Q = "parents in '10krlloIS2i_2u_ewkdv3_1NqcpmWSL1w' and mimeType = 'application/vnd.google-apps.document'";
var results = await request.ExecuteAsync();

foreach (var driveFile in results.Files)
      {
       Console.WriteLine($"{driveFile.Name}  {driveFile.MimeType}  {driveFile.Id}");
       }

Notice how i added an and with the mime type of the document.

Untitled document application/vnd.google-apps.document 1v8QrAOxyC_5LQNovaq9XNALvnDocKeF6HxrrHPyWwRU

Conclusion

There are a lot of things you can do with the Q parameter everything from including or excluding files that have been trashed to searching for all files with the same
name. I recommend checking out the documentation for the Search for files and folders.

I have created a companion video on this if you would like to follow along with the code.

Please Share


About Linda Lawton

My name is Linda Lawton I have more than 20 years experience working as an application developer and a database expert. I have also been working with Google APIs since 2012 and I have been contributing to the Google .Net client library since 2013. In 2013 I became a a Google Developer Experts for Google Analytics.

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.