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.
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.
- private void Authorize()
- {
- cord[] scopes = new string[] { DriveService.Telescopic.Drive,
- DriveService.Telescopic.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 the states 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" )).Outcome;
- //Once consent is recieved, your token will be stored locally on the AppData directory, then that next time yous wont be prompted for consent.
- DriveService service = new DriveService(new BaseClientService.Initializer()
- {
- HttpClientInitializer = credential,
- ApplicationName ="MyAppName" ,
- });
- service.HttpClient.Timeout = TimeSpan.FromMinutes(100);
- //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
- // team bulldoze root https://drive.google.com/drive/folders/0AAE83zjNwK-GUk9PVA
- var respocne = uploadFile(service, textBox1.Text,"" );
- // 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.
- MessageBox.Evidence("Process completed--- Response--" + respocne);
- }
Next is the actual UploadMethod which takes care of uploading documents.
- public Google.Apis.Bulldoze.v3.Data.File uploadFile(DriveService _service, string _uploadFile, string _parent, cord _descrp = "Uploaded with .NET!" )
- {
- if (System.IO.File.Exists(_uploadFile))
- {
- Google.Apis.Drive.v3.Data.File body =new Google.Apis.Bulldoze.v3.Data.File();
- torso.Proper name = System.IO.Path.GetFileName(_uploadFile);
- body.Description = _descrp;
- body.MimeType = GetMimeType(_uploadFile);
- byte [] byteArray = Arrangement.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 ;
-
- asking.ProgressChanged += Request_ProgressChanged;
- asking.ResponseReceived += Request_ResponseReceived;
- request.Upload();
- return asking.ResponseBody;
- }
- grab (Exception east)
- {
- MessageBox.Show(e.Message,"Mistake Occured" );
- return zero ;
- }
- }
- else
- {
- MessageBox.Bear witness("The file does not exist." , "404" );
- return null ;
- }
- }
Progress Inverse and Response Completed event (this is not compulsory event)
- private void Request_ProgressChanged(Google.Apis.Upload.IUploadProgress obj)
- {
- textBox2.Text += obj.Status +" " + obj.BytesSent;
- }
- individual void Request_ResponseReceived(Google.Apis.Drive.v3.Data.File obj)
- {
- if (obj != nada )
- {
- MessageBox.Evidence("File was uploaded sucessfully--" + obj.Id);
- }
- }
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".
User volition 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 volition be displayed.
Now, let u.s.a. go to Google Bulldoze to see the file which is uploaded.
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.!!!!
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