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.
- private void SearchButton_Click(object sender, EventArgs e)
- {
- DriveService _service = GetDriveServce();
- SearchFiles(_service, textBox3.Text);
-
- }
Next method is to Get Drive API Service. (make sure you replace clientId and clientSecret with actual one)
- private DriveService GetDriveServce()
- {
-
- string[] scopes = new string[] { DriveService.Scope.Drive,
- DriveService.Scope.DriveFile,};
- var clientId = "12334567890154-5isfgs6sduhd0tcg4qmadrjqg1udagmgapps.googleusercontent.com";
- var clientSecret = "ksdklfklas2lskj_asdklfjaskla-";
-
- var credential = GoogleWebAuthorizationBroker.AuthorizeAsync(new ClientSecrets
- {
- ClientId = clientId,
- ClientSecret = clientSecret
- }, scopes,
- Environment.UserName, CancellationToken.None, new FileDataStore("MyAppsToken")).Result;
-
-
- DriveService _service = new DriveService(new BaseClientService.Initializer()
- {
- HttpClientInitializer = credential,
- ApplicationName = "MyAppName",
-
- });
- return _service;
- }
Next is main method which queries Google Drive and searches files.
- public Google.Apis.Drive.v3.Data.File SearchFiles(DriveService _service, string query)
- {
- try
- {
-
-
- string pageToken = null;
-
-
-
-
- var request = _service.Files.List();
- request.Q = query;
-
-
-
-
- request.Fields = "nextPageToken, files(id, name,parents,mimeType)";
-
- request.PageToken = pageToken;
- // Add this if you are facing certificate issue or not able to connect from you machine
- System.Net.ServicePointManager.ServerCertificateValidationCallback = delegate (object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { return true; };
- var result = request.Execute();
-
- if (result.Files.Count > 0)
- {
- string Output = "";
- DataTable dt = new DataTable();
-
- dt.Columns.Add("File Name");
- dt.Columns.Add("File Type");
- dt.Columns.Add("File ID");
- foreach (Google.Apis.Drive.v3.Data.File file in result.Files)
- {
- DataRow dr = dt.NewRow();
- dr["File Name"] = file.Name;
- dr["File Type"] = file.MimeType;
- dr["File ID"] = file.Id;
- dt.Rows.Add(dr);
- }
- dataGridView1.DataSource = dt;
- }
- else
- {
- MessageBox.Show("No file found");
- }
- }
- catch (Exception ex)
- {
- throw ex;
- }
- return null;
-
- }
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.
If you are not authenticated already, you would need to authenticate via OAuth Google login process.
The User Consent screen will be displayed; provide access to Google Drive.
Once the process is completed, you will get results in the grid if your drive contains files.
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'
- 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
- 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