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.


  • 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. 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 link and add references.
  • Below is the screenshot of DLLs required.

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.
private void Authorize()  
              string[] scopes = new string[] { DriveService.Scope.Drive,  
              var clientId = "";      // From  
              var clientSecret = "ksdklfklas2lskj_asdklfjaskla-";          // From  
             // here is where we Request the user to give us access, or use the Refresh Token that was previously stored in %AppData%  
              var credential = GoogleWebAuthorizationBroker.AuthorizeAsync(new ClientSecrets  
                  ClientId = clientId,  
                  ClientSecret = clientSecret  
              Environment.UserName,CancellationToken.None,new FileDataStore("MyAppsToken")).Result;  
              //Once consent is recieved, your token will be stored locally on the AppData directory, so that next time you wont be prompted for consent.   
              DriveService service = new DriveService(new BaseClientService.Initializer()  
                  HttpClientInitializer = credential,  
                  ApplicationName = "MyAppName",  
            service.HttpClient.Timeout = TimeSpan.FromMinutes(100);  
            //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  
            // team drive root   
            var respocne = uploadFile(service, textBox1.Text, "");  
            // 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.
            MessageBox.Show("Process completed--- Response--" + respocne);  


Next is the actual UploadMethod which takes care of uploading documents.

public Google.Apis.Drive.v3.Data.File uploadFile(DriveService _service, string _uploadFile, string _parent, string _descrp = "Uploaded with .NET!")  
           if (System.IO.File.Exists(_uploadFile))  
               Google.Apis.Drive.v3.Data.File body = new Google.Apis.Drive.v3.Data.File();  
               body.Name = System.IO.Path.GetFileName(_uploadFile);  
               body.Description = _descrp;  
               body.MimeType = GetMimeType(_uploadFile);        
              // 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)
               byte[] byteArray = System.IO.File.ReadAllBytes(_uploadFile);  
               System.IO.MemoryStream stream = new System.IO.MemoryStream(byteArray);  
                   FilesResource.CreateMediaUpload request = _service.Files.Create(body, stream, GetMimeType(_uploadFile));  
                   request.SupportsTeamDrives = true;   
                   // You can bind event handler with progress changed event and response recieved(completed event)

                   request.ProgressChanged += Request_ProgressChanged;  
                   request.ResponseReceived += Request_ResponseReceived;  
                   return request.ResponseBody;  
               catch (Exception e)  
                   MessageBox.Show(e.Message, "Error Occured");  
                   return null;  
               MessageBox.Show("The file does not exist.", "404");  
               return null;  


Progress Changed and Response Completed event (this is not compulsory event)

private void Request_ProgressChanged(Google.Apis.Upload.IUploadProgress obj)  
           textBox2.Text +=  obj.Status + " " + obj.BytesSent;    
       private void Request_ResponseReceived(Google.Apis.Drive.v3.Data.File obj)  
           if(obj != null)  
               MessageBox.Show("File was uploaded sucessfully--" + obj.Id);  


We have all of our code snippets ready. Now, let us run the code. Run the application, browse the file, and click on “Upload”.

User will be asked for authentication. A new browser window would open. Enter your Google credentials.

The User Consent screen will be displayed; provide access to Google Drive.

Once the process is completed, a success message will be displayed.

Now, let us go to Google Drive to see the file which is uploaded.


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.!!!!
Note: This article was orignally published at this link.
(Visited 83 times, 1 visits today)