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.
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);
- }
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);
-
- 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;
-
- 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;
- }
- }
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.
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.!!!!