In Focus

How To Upload A File To Google Drive Using Google API From .NET

In this article, you will learn how to upload a file to Google Drive using Google API from .NET.

In this article, we will learn how to upload a document to Google Drive using the .NET Google API Library.
 
I am assuming that you have 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 the operations like creating a new file, uploading, deleting, searching file, getting file, etc. using Google Drive API.
 

Prerequisites

  • Enable Google Drive to generate the client Id and client secret (crendentials.json) 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.
How To Upload A File To Google Drive Using Google API From .NET 
 
For our scenario, I have created a Windows application which allows the user to browse the file and upload option to his drive. 
 
Let us start with code snippets.
  1. private void Authorize()  
  2.         {  
  3.               string[] scopes = new string[] { DriveService.Scope.Drive,  
  4.                                DriveService.Scope.DriveFile,};  
  5.               var clientId = "12345678-kiwwjelkrklsjdkljklaflkjsdjasdkhw.apps.googleusercontent.com";      // From https://console.developers.google.com  
  6.               var clientSecret = "ksdklfklas2lskj_asdklfjaskla-";          // From https://console.developers.google.com  
  7.              // here is where we Request the user to give us access, or use the Refresh Token that was previously stored in %AppData%  
  8.               var credential = GoogleWebAuthorizationBroker.AuthorizeAsync(new ClientSecrets  
  9.               {  
  10.                   ClientId = clientId,  
  11.                   ClientSecret = clientSecret  
  12.               },scopes,  
  13.               Environment.UserName,CancellationToken.None,new FileDataStore("MyAppsToken")).Result;  
  14.               //Once consent is recieved, your token will be stored locally on the AppData directory, so that next time you wont be prompted for consent.   
  15.   
  16.               DriveService service = new DriveService(new BaseClientService.Initializer()  
  17.               {  
  18.                   HttpClientInitializer = credential,  
  19.                   ApplicationName = "MyAppName",  
  20.   
  21.               });  
  22.             service.HttpClient.Timeout = TimeSpan.FromMinutes(100);  
  23.             //Long Operations like file uploads might timeout. 100 is just precautionary value, can be set to any reasonable value depending on what you use your service for  
  24.   
  25.             // team drive root https://drive.google.com/drive/folders/0AAE83zjNwK-GUk9PVA   
  26.   
  27.             var respocne = uploadFile(service, textBox1.Text, "");  
  28.             // Third parameter is empty it means it would upload to root directory, if you want to upload under a folder, pass folder's id here.
  29.             MessageBox.Show("Process completed--- Response--" + respocne);  
  30.         }  
Next is the actual UploadMethod which takes care of uploading documents.
  1. public Google.Apis.Drive.v3.Data.File uploadFile(DriveService _service, string _uploadFile, string _parent, string _descrp = "Uploaded with .NET!")  
  2.        {  
  3.            if (System.IO.File.Exists(_uploadFile))  
  4.            {  
  5.                Google.Apis.Drive.v3.Data.File body = new Google.Apis.Drive.v3.Data.File();  
  6.                body.Name = System.IO.Path.GetFileName(_uploadFile);  
  7.                body.Description = _descrp;  
  8.                body.MimeType = GetMimeType(_uploadFile);        
  9.               // body.Parents = new List<string> { _parent };// UN comment if you want to upload to a folder(ID of parent folder need to be send as paramter in above method)
  10.                byte[] byteArray = System.IO.File.ReadAllBytes(_uploadFile);  
  11.                System.IO.MemoryStream stream = new System.IO.MemoryStream(byteArray);  
  12.                try  
  13.                {  
  14.                    FilesResource.CreateMediaUpload request = _service.Files.Create(body, stream, GetMimeType(_uploadFile));  
  15.                    request.SupportsTeamDrives = true;   
  16.                    // You can bind event handler with progress changed event and response recieved(completed event)
  17.                    request.ProgressChanged += Request_ProgressChanged;  
  18.                    request.ResponseReceived += Request_ResponseReceived;  
  19.                    request.Upload();  
  20.                    return request.ResponseBody;  
  21.                }  
  22.                catch (Exception e)  
  23.                {  
  24.                    MessageBox.Show(e.Message, "Error Occured");  
  25.                    return null;  
  26.                }  
  27.            }  
  28.            else  
  29.            {  
  30.                MessageBox.Show("The file does not exist.""404");  
  31.                return null;  
  32.            }  
  33.        }  
Progress Changed and Response Completed event (this is not compulsory event)
  1. private void Request_ProgressChanged(Google.Apis.Upload.IUploadProgress obj)  
  2.        {  
  3.            textBox2.Text +=  obj.Status + " " + obj.BytesSent;    
  4.        }  
  5.   
  6.        private void Request_ResponseReceived(Google.Apis.Drive.v3.Data.File obj)  
  7.        {  
  8.            if(obj != null)  
  9.            {  
  10.                MessageBox.Show("File was uploaded sucessfully--" + obj.Id);  
  11.            }  
  12.        }  
We have all of our code snippets ready. Now, let us run the code. Run the application, browse the file, and click on "Upload".
 
How To Upload A File To Google Drive Using Google API From .NET
 
User will be asked for authentication. A new browser window would open. Enter your Google credentials.
 
How To Upload A File To Google Drive Using Google API From .NET
 
The User Consent screen will be displayed; provide access to Google Drive.
 
How To Upload A File To Google Drive Using Google API From .NET
 
Once the process is completed, a success message will be displayed.
 
How To Upload A File To Google Drive Using Google API From .NET
 
Now, let us go to Google Drive to see the file which is uploaded.
 
How To Upload A File To Google Drive Using Google API From .NET
 

Summary

 
This article gave you a general idea on how to use Google Drive API. There are other APIs available like getting files list, get file, delete file, setting permission, etc. You can follow this link for more details.
 
Hope this helps...Happy coding.!!!!