How To Search Files On Google Drive Progamatically From .NET Using Drive API

Google, like any other service provider, has provided APIs to interact with its services. I am assuming that you have the basic knowledge of Google Drive API. If not, please go through this link. Google has provided a .NET Library to interact with Google Drive. We can perform operations like creating a new file, uploading, deleting, searching file, getting a file and its metadata etc. using Google Drive API.
 
This is the third article in a series of exploring Google API from .NET. You can find links to other articles in the end of this article.
 
We can search for files on Google Drive by
  • Filename
  • Text in the content of the file
  • Writeable by
  • Search in particular folder
  • Files which are trashed
  • Search based on creation and modification date
  • and many others......
Prerequisites
  • Enable Google Drive to generate the client Id and client secret which will be used later. There are many articles already available on how to do this. So, I won't explain it here. Please refer to the below links for quick reference.

    https://developers.google.com/drive/api/v3/quickstart/dotnet

    Please note that if you are doing this with ASP.NET, you have to generate the client id and secret for the web application.
  • Create a Windows Console application or web application (using Visual Studio).

  • Add a reference to Google API dll via NuGet package. Alternatively, you can download it manually from nuget.org link and add references.

  • Below is the screenshot of DLLs required.
Use Case
  • Create a Windows application, provide a text box to enter a query, search button, and GridView to show results.
  • Search results will be displayed in GridView with 3 columns - File Name, File Type, and File Id.
Let us start with code snippets. I have segregated code into methods for easy understanding and reusability.
 
Below method is Search button-click event handler. 
  1. private void SearchButton_Click(object sender, EventArgs e)  
  2.        {  
  3.            DriveService _service = GetDriveServce();  
  4.            SearchFiles(_service, textBox3.Text);  
  5.   
  6.        }  

Next method is to Get Drive API Service. (make sure you replace clientId and clientSecret with actual one)

  1. private DriveService GetDriveServce()  
  2.         {  
  3.   
  4.             string[] scopes = new string[] { DriveService.Scope.Drive,  
  5.                               DriveService.Scope.DriveFile,};  
  6.             var clientId = "12334567890154-5isfgs6sduhd0tcg4qmadrjqg1udagmgapps.googleusercontent.com";      // From https://console.developers.google.com  
  7.             var clientSecret = "ksdklfklas2lskj_asdklfjaskla-";          // From https://console.developers.google.com  
  8.                                                                     // here is where we Request the user to give us access, or use the Refresh Token that was previously stored in %AppData%  
  9.             var credential = GoogleWebAuthorizationBroker.AuthorizeAsync(new ClientSecrets  
  10.             {  
  11.                 ClientId = clientId,  
  12.                 ClientSecret = clientSecret  
  13.             }, scopes,  
  14.             Environment.UserName, CancellationToken.None, new FileDataStore("MyAppsToken")).Result;  
  15.             //Once consent is recieved, your token will be stored locally on the AppData directory, so that next time you wont be prompted for consent.   
  16.   
  17.             DriveService _service = new DriveService(new BaseClientService.Initializer()  
  18.             {  
  19.                 HttpClientInitializer = credential,  
  20.                 ApplicationName = "MyAppName",  
  21.   
  22.             });  
  23.             return _service;  
  24.         }  

Next is main method which queries Google Drive and searches files.

  1. public Google.Apis.Drive.v3.Data.File SearchFiles(DriveService _service, string query)  
  2.        {  
  3.            try  
  4.            {  
  5.                //check if folder exists  
  6.   
  7.                string pageToken = null;  
  8.   
  9.                //EXample of query to find spreadsheet with filename = something and trashed is false(not deleted)  
  10.                //string query = "mimeType='application/vnd.google-apps.spreadsheet' and trashed = false and name = '" + filename + "'";  
  11.   
  12.                var request = _service.Files.List();  
  13.                request.Q = query;  
  14.                //request.Corpora = "teamDrive"; //  Add this if you are searching in TeamDrive  
  15.                //request.TeamDriveId = teamDriveId; // Add this if you are searching in TeamDrive  
  16.                //request.SupportsTeamDrives = true; // Add this if you are searching in TeamDrive  
  17.                //request.IncludeTeamDriveItems = true; // Add this if you are searching in TeamDrive  
  18.                request.Fields = "nextPageToken, files(id, name,parents,mimeType)";  
  19.   
  20.                request.PageToken = pageToken;  
  21.                // Add this if you are facing certificate issue or not able to connect from you machine
  22.                System.Net.ServicePointManager.ServerCertificateValidationCallback = delegate (object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { return true; };  
  23.                var result = request.Execute();  
  24.   
  25.                if (result.Files.Count > 0)  
  26.                {  
  27.                    string Output = "";  
  28.                    DataTable dt = new DataTable();  
  29.   
  30.                    dt.Columns.Add("File Name");  
  31.                    dt.Columns.Add("File Type");  
  32.                    dt.Columns.Add("File ID");  
  33.                    foreach (Google.Apis.Drive.v3.Data.File file in result.Files)  
  34.                    {  
  35.                        DataRow dr = dt.NewRow();  
  36.                        dr["File Name"] = file.Name;  
  37.                        dr["File Type"] = file.MimeType;  
  38.                        dr["File ID"] = file.Id;  
  39.                        dt.Rows.Add(dr);  
  40.                    }  
  41.                    dataGridView1.DataSource = dt;                       
  42.                }  
  43.                else  
  44.                {  
  45.                    MessageBox.Show("No file found");  
  46.                }  
  47.            }  
  48.            catch (Exception ex)  
  49.            {  
  50.                throw ex;  
  51.            }  
  52.            return null;  
  53.   
  54.        }  

 Let us understand some points from the above method.

  • We are using the _service.Files.List() method to create request. This method contains properties definitions which we need to set when making service call.
  • request.Fields - We are only getting 3 fields here from Files. Refer this link to know about other fields available.
  • You can pass other parameters in request object which are optional. Refer to this link to know about other parameters and its details.
  • For searching files under teamDrive, some parameters need to be passed (commented in the above method)
No,w we have our code snippets. Let's try this now.
 
Run the application. Enter search query name = "helloworld" and click on Search. The query will try to find files with the name 'helloworld'. We will see in detail how to form this query.
 
How To Search Files On Google Drive Progamatically From .NET Using Drive API
 
If you are not authenticated already, you would need to authenticate via OAuth Google login process.
 
How To Search Files On Google Drive Progamatically From .NET Using Drive API
 
The User Consent screen will be displayed; provide access to Google Drive.
 
How To Search Files On Google Drive Progamatically From .NET Using Drive API
 
Once the process is completed, you will get results in the grid if your drive contains files.
 
How To Search Files On Google Drive Progamatically From .NET Using Drive API
 
This concludes that our code is working fine. Now let us understand and see how to form search queries.
 
We are using the request.Q parameter to set search query. This search query can be formed using one or more search clauses. Each search clause is made of 3 parts.
  • Field - Attribute of the file that is searched, e.g., the attribute name of the file.
  • Operator - Test that is performed on the data to provide a match, e.g., contains.
  • Value - The content of the attribute that is tested, e.g. the name of the file helloworld.
For supported field, operator and values type refer to this link.
 
Let us see some examples of common search queries requirements (below are the examples from this link) to understand how can we form queries. 
  • Search for files with the name "hello"
name = 'hello'
  • Search for folders using the folder-specific MIME type
mimeType = 'application/vnd.google-apps.folder'
  • Search for files that are not folders
mimeType != 'application/vnd.google-apps.folder'
  • Search for files with a name containing the words "hello" and "goodbye"
name contains 'hello' and name contains 'goodbye'
  • Search for files with a name that does not contain the word "hello"
not name contains 'hello'
  •  Search for files containing the word "hello" in the content
fullText contains 'hello'
  • Search for files not containing the word "hello" in the content
not fullText contains 'hello'
  • Search for files containing the exact phrase "hello world" in the content
fullText contains '"hello world"'
fullText contains '"hello_world"'
  • Search for files with a query containing the "" character (e.g., "\authors")
fullText contains '\\authors'
'[email protected]' in writers
'[email protected]' in writers
  • Search for ID 1234567 in the parents collection. This finds all files and folders located directly in the folder whose ID is 1234567.
'1234567' in parents
  • Search for the alias ID appDataFolder in the parents collection. This finds all files and folders located directly under the Application Data folder.
'appDataFolder' in parents
'[email protected]' in writers and '[email protected]' in writers
  • Search for files containing the text "important" which are in the trash
fullText contains 'important' and trashed = true
  • Search for files modified after June 4th, 2012
modifiedTime > '2012-06-04T12:00:00' // default time zone is UTC
modifiedTime > '2012-06-04T12:00:00-08:00'
  • Search for files shared with the authorized user with "hello" in the name
sharedWithMe and name contains 'hello'
  • Search for files with a custom file property named additionalID with the value 8e8aceg2af2ge72e78.
appProperties has { key='additionalID' and value='8e8aceg2af2ge72e78' }
  • Search for files that have not been shared with anyone or domains (only private, or shared with specific users or groups)
 visibility = 'limited'
With this I would like to conclude this article, I hope this will help you get started.
 
P.S - Reference to other articles related to Google API and .NET