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.
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,
- DriveService.Scope.DriveFile,};
- var clientId = "12345678-kiwwjelkrklsjdkljklaflkjsdjasdkhw.apps.googleusercontent.com"; // From https://console.developers.google.com
- var clientSecret = "ksdklfklas2lskj_asdklfjaskla-"; // From https://console.developers.google.com
- // 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
- },scopes,
- 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 https://drive.google.com/drive/folders/0AAE83zjNwK-GUk9PVA
- 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);
- }
- 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);
- try
- {
- 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;
- request.Upload();
- return request.ResponseBody;
- }
- catch (Exception e)
- {
- MessageBox.Show(e.Message, "Error Occured");
- return null;
- }
- }
- else
- {
- MessageBox.Show("The file does not exist.", "404");
- return null;
- }
- }
- 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.

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.!!!!

Kuppu SwamiPosted Feb 5, 2024, 11:21 AM
I am having doubts on creating the client ids in drive
Yigit YektinPosted Jul 25, 2023, 1:29 PM
Can we skip the sign in part? I need that the user directly uploads with my tokens.
Ashish SharmaPosted Feb 19, 2022, 10:21 AM
Something is not working, Error: system.net.httplistenerexception the network location cannot be reached
Jamie DewitzPosted Feb 7, 2022, 5:51 PM
How do you browse the computer? I don't see any code for Browse click or anything for the upload button. Are there pieces missing from this tutorial?
jose silveiraPosted Jan 13, 2022, 6:08 PM
Can you share the project i'n studing c# and i want to learn
BalamuruganPosted Jun 21, 2021, 8:50 AM
Hi. It is amazing. Something is not working well in Google Slides. I am a c#.net developer. Here is the code to insert the picture in the google slides. But I can not able to set the position, width, and height. Request req = new Request(); req.CreateImage = new CreateImageRequest(); req.CreateImage.Url = this.strImagePath; req.CreateImage.ElementProperties = new PageElementProperties(); req.CreateImage.ElementProperties.PageObjectId = this.GetPresentationObjectId(this.internal_intSlideIndex); /* req.CreateImage.ElementProperties.Size = new Google.Apis.Slides.v1.Data.Size(); req.CreateImage.ElementProperties.Size.Height.Magnitude = 3000000; req.CreateImage.ElementProperties.Size.Height.Unit = "EMNU"; req.CreateImage.ElementProperties.Size.Width.Magnitude = 3000000; req.CreateImage.ElementProperties.Size.Width.Unit = "EMNU"; req.CreateImage.ElementProperties.Transform = new AffineTransform(); req.CreateImage.ElementProperties.Transform.Unit = "EMNU"; req.CreateImage.ElementProperties.Transform.ScaleX = 1.55; req.CreateImage.ElementProperties.Transform.ScaleY = 1.10; req.CreateImage.ElementProperties.Transform.TranslateX = 4671925; req.CreateImage.ElementProperties.Transform.TranslateY = 450150;*/
Sushil AgarwalPosted Mar 2, 2021, 6:30 PM
sorry, but i Think progresschanged procedure would be better written line this private void Request_ProgressChanged(Google.Apis.Upload.IUploadProgress obj) { if (obj.Status != Google.Apis.Upload.UploadStatus.Completed) textBox2.Text += obj.Status + " " + obj.BytesSent; } private void Request_ResponseReceived(Google.Apis.Drive.v3.Data.File obj) { if (obj == null) { MessageBox.Show("Upload Failed !!!"); } } . it helped me to get responce which was coming null due to cross thread operation after process completed and progresschanged trying to write text2.text was getting in upload try catch blcok
Jonas DufekPosted Jan 2, 2020, 11:18 AM
You're missing the GetMimeType method: private static string GetMimeType(string fileName) { string mimeType = "application/unknown"; string ext = System.IO.Path.GetExtension(fileName).ToLower(); Microsoft.Win32.RegistryKey regKey = Microsoft.Win32.Registry.ClassesRoot.OpenSubKey(ext); if (regKey != null && regKey.GetValue("Content Type") != null) mimeType = regKey.GetValue("Content Type").ToString(); System.Diagnostics.Debug.WriteLine(mimeType); return mimeType; }
Prakash KoiralaPosted Dec 3, 2019, 4:03 AM
Request_ProgressChanged not written in my textbox why? But i am getting the value in MessageBox.Show(). public void Request_ProgressChanged(Google.Apis.Upload.IUploadProgress obj) { // MessageBox.Show(obj.Status + " " + obj.BytesSent); GDriveProgressTxt.Text += obj.Status + " " + obj.BytesSent; }
Mohsin AzamPosted Jun 12, 2019, 2:34 AM
Good article,Is there any option to search contents in google drive files?
Madan ShekarPosted Jun 11, 2019, 8:36 AM
Thanks for sharing valuable information