Google Drive Rest Api Upload Csv Authentication

  • Updated date Jun 11, 2019
  • 100.9k
  • eight

In this article, yous will larn how to upload a file to Google Drive using Google API from .Net.

In this commodity, nosotros will learn how to upload a certificate to Google Drive using the .NET Google API Library.

I am assuming that you accept bones knowledge of Google Drive API. If non, delight 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 exist used subsequently. There are many manufactures already available on how to do this. And so, I won't explain it here. Please refer to the below links for quick reference.

    https://developers.google.com/bulldoze/api/v3/quickstart/dotnet

    Please notation that if you are doing this with ASP.Internet, yous have to generate the customer id and secret for the spider web application.

  • Create a Windows Console awarding or web application (using Visual Studio).
  • Add a reference to Google API dll via NuGet package. Alternatively, you tin download information technology 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 accept created a Windows application which allows the user to scan the file and upload option to his drive.

Let u.s.a. offset with code snippets.

  1. private void Authorize()
  2.         {
  3.               cord[] scopes = new string[] { DriveService.Telescopic.Drive,
  4.                                DriveService.Telescopic.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 the states 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" )).Outcome;
  14.               //Once consent is recieved, your token will be stored locally on the AppData directory, then that next time yous wont be prompted for consent.
  15.               DriveService service = new DriveService(new BaseClientService.Initializer()
  16.               {
  17.                   HttpClientInitializer = credential,
  18.                   ApplicationName ="MyAppName" ,
  19.               });
  20.             service.HttpClient.Timeout = TimeSpan.FromMinutes(100);
  21.             //Long  Operations similar file uploads might timeout. 100 is just precautionary value, can be gear up to any reasonable value depending on what you use your service for
  22.             // team bulldoze root https://drive.google.com/drive/folders/0AAE83zjNwK-GUk9PVA
  23.             var respocne = uploadFile(service, textBox1.Text,"" );
  24.             // Tertiary parameter is empty information technology means it would upload to root directory, if you want to upload under a folder, pass folder's id here.
  25.             MessageBox.Evidence("Process completed--- Response--"  + respocne);
  26.         }

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

  1. public  Google.Apis.Bulldoze.v3.Data.File uploadFile(DriveService _service, string  _uploadFile, string  _parent, cord  _descrp = "Uploaded with .NET!" )
  2.        {
  3. if  (System.IO.File.Exists(_uploadFile))
  4.            {
  5.                Google.Apis.Drive.v3.Data.File body =new  Google.Apis.Bulldoze.v3.Data.File();
  6.                torso.Proper name = System.IO.Path.GetFileName(_uploadFile);
  7.                body.Description = _descrp;
  8.                body.MimeType = GetMimeType(_uploadFile);
  9. byte [] byteArray = Arrangement.IO.File.ReadAllBytes(_uploadFile);
  10.                System.IO.MemoryStream stream =new  System.IO.MemoryStream(byteArray);
  11. try
  12.                {
  13.                    FilesResource.CreateMediaUpload request = _service.Files.Create(body, stream, GetMimeType(_uploadFile));
  14.                    request.SupportsTeamDrives =true ;

  15.                    asking.ProgressChanged += Request_ProgressChanged;
  16.                    asking.ResponseReceived += Request_ResponseReceived;
  17.                    request.Upload();
  18. return  asking.ResponseBody;
  19.                }
  20. grab  (Exception east)
  21.                {
  22.                    MessageBox.Show(e.Message,"Mistake Occured" );
  23. return zero ;
  24.                }
  25.            }
  26. else
  27.            {
  28.                MessageBox.Bear witness("The file does not exist." , "404" );
  29. return null ;
  30.            }
  31.        }

Progress Inverse 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. individual void  Request_ResponseReceived(Google.Apis.Drive.v3.Data.File obj)
  6.        {
  7. if (obj != nada )
  8.            {
  9.                MessageBox.Evidence("File was uploaded sucessfully--"  + obj.Id);
  10.            }
  11.        }

We have all of our code snippets set up. At present, let u.s.a. run the lawmaking. Run the awarding, scan the file, and click on "Upload".

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

User volition 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 volition be displayed.

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

Now, let u.s.a. go to Google Bulldoze to see the file which is uploaded.

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

Summary

This commodity gave you a general idea on how to use Google Drive API. There are other APIs available similar getting files list, get file, delete file, setting permission, etc. Y'all tin can follow this link for more than details.

Hope this helps...Happy coding.!!!!

martinstictied.blogspot.com

Source: https://www.c-sharpcorner.com/article/how-to-upload-a-file-to-google-drive-using-google-api-from-net/

0 Response to "Google Drive Rest Api Upload Csv Authentication"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel