Google Drive Rest Api Upload File Another Account
An updated version of this tutorial for Google Drive API V3 can be institute How to upload a file to Google Bulldoze with C# .internet (Updated 2021). I recommend switching to Google Bulldoze API v3 and not using this tutorial.
Have yous been trying to connect your website or application to Google Drive? Would yous like to see a list of files or a list of Directories stored on Google Bulldoze? Would you like to Upload a file to Google Bulldoze or download a file from Google drive using C# .Net using Visual Studio. In this tutorial series, we volition be looking into the Google Bulldoze API, using the Google .cyberspace Customer library which makes accessing Google APIs much simpler. There are a lot of things you lot tin do with the Google Bulldoze API, List files and folders, Download files, Upload files, Change Files, Copy files, Delete Files, Trash Files, Create directory's, delete directory's. There is fifty-fifty a version of %appdata% on Google Drive where yous can store your awarding specific files for each user.
Contents
- 1 Five function Tutorial Series
- 2 Restringing your application.
- three Projection Setup
- 4 Authentication
- v Upload
- 5.1 Directory
- 5.two Files
- 6 Update
-
- 6.0.one Patch
-
- 7 Delete
- eight Trash
- ix Concision
Five part Tutorial Series
- Google Bulldoze API with C# .cyberspace – Hallmark
- Google Drive API with C# .net – Files – Files, directories, search
- Google Drive API with C# .internet – Upload, update, patch, delete, trash
- Google Bulldoze API with C# .net – Download
- Google Bulldoze API with C# .net – File Permissions
- Google Drive API with C# .net – Sample project
Restringing your application.
Like with most of the Google APIs you lot need to be authenticated in order to connect to them. To do that y'all must outset annals your application on Google Programmer panel. Under APIs exist sure to enable the Google Drive API and Google Drive SDK, every bit always don't forget to add a product proper name and e-mail address on the consent screen form.
Project Setup
Make sure your project is at least prepare to .net 4.0.
Add the post-obit NuGet Package
PM> Install-Package Google.Apis.Drive.v2
Y'all volition probably demand virtually of these using's
using System; using Google.Apis.Drive.v2; using Google.Apis.Auth.OAuth2; using System.Threading; using Google.Apis.Util.Store; using Google.Apis.Services; using Google.Apis.Drive.v2.Data; using Organisation.Collections.Generic;
Authentication
This tutorial assumes that you lot have already read the tutorial about Google Drive API with C# .net – Authentication. I will not be going into how to create a valid Drive service if yous oasis't created one already please go read that tutorial then come back hither.
Now nosotros take a drive service that we can preform perform though.
Upload
Directory
Call up directory'southward are goose egg just files with a different mime type. The following method will create a new let yous to create a new directory. Send parent = root if you would like it at the top directory. Other wise information technology must exist a valid directory file resource id, you can get this using listing with search to detect the directory you are looking for.
/////// Create a new Directory. /// Documentation: https://developers.google.com/bulldoze/v2/reference/files/insert /// /// a Valid authenticated DriveService /// The title of the file. Used to identify file or folder name. /// A short description of the file. /// Collection of parent folders which contain this file. /// Setting this field will put the file in all of the provided folders. root binder. ///public static File createDirectory(DriveService _service, cord _title, string _description, string _parent) { File NewDirectory = null; // Create metaData for a new Directory File body = new File(); body.Championship = _title; body.Description = _description; trunk.MimeType = "awarding/vnd.google-apps.folder"; body.Parents = new List () { new ParentReference() { Id = _parent } }; try { FilesResource.InsertRequest request = _service.Files.Insert(body); NewDirectory = asking.Execute(); } catch (Exception e) { Panel.WriteLine("An mistake occurred: " + e.Message); } return NewDirectory; }
Files
Remember from creating a directory in order to upload a file you accept to be able to tell Google what its mime-type is. I have a picayune method here that endeavour's to effigy that out. Only send it the file proper noun. Note: When uploading a file to Google Bulldoze if the name of the file is the same name as a file that is already there. Google Bulldoze just uploads it anyhow, the file that was there is not updated you merely end upwards with 2 files with the same name. It only checks based on the fileId not based upon the file proper noun. If you want to Update a file you demand to utilise the Update command nosotros will bank check that after.
// tries to figure out the mime type of the file. individual static string GetMimeType(string fileName) { string mimeType = "application/unknown"; string ext = Arrangement.IO.Path.GetExtension(fileName).ToLower(); Microsoft.Win32.RegistryKey regKey = Microsoft.Win32.Registry.ClassesRoot.OpenSubKey(ext); if (regKey != null && regKey.GetValue("Content Type") != zip) mimeType = regKey.GetValue("Content Blazon").ToString(); return mimeType; }
With that we can proceed.
////// Uploads a file /// Documentation: https://developers.google.com/drive/v2/reference/files/insert /// /// a Valid authenticated DriveService /// path to the file to upload /// Drove of parent folders which comprise this file. /// Setting this field will put the file in all of the provided folders. root folder. ///If upload succeeded returns the File resource of the uploaded file /// If the upload fails returns null public static File uploadFile(DriveService _service, string _uploadFile, string _parent) { if (System.IO.File.Exists(_uploadFile)) { File trunk = new File(); torso.Title = Organization.IO.Path.GetFileName(_uploadFile); body.Clarification = "File uploaded past Diamto Drive Sample"; body.MimeType = GetMimeType(_uploadFile); body.Parents = new List() { new ParentReference() { Id = _parent } }; // File's content. byte[] byteArray = System.IO.File.ReadAllBytes(_uploadFile); System.IO.MemoryStream stream = new System.IO.MemoryStream(byteArray); try { FilesResource.InsertMediaUpload request = _service.Files.Insert(body, stream, GetMimeType(_uploadFile)); request.Upload(); render request.ResponseBody; } catch (Exception east) { Panel.WriteLine("An fault occurred: " + e.Message); return null; } } else { Panel.WriteLine("File does not be: " + _uploadFile); render null; } }
Just like with creating a directory nosotros need to supply our meta data information. We are using the GetMimeType method to find out the files mimetype. And so we are loading the File into a MemoryStream that we can apply to transport to service.Files.Insert. In one case the file is done uploading you tin get the request.ResponseBody and bank check for any errors. If a file.id is returned you know your file has now been uploaded.
Update
Google Drive is a little strange in my opinion. If you lot accept the same fine and upload it once more, yous terminate upward with two files. Personally i would rather see the first one over written, just thats not how Google has chosen to do things. So that is where update comes in. If you want to brand a change to a file and so you will need to update the file. To update a file in Google drive you lot will need the file resource id of the file you would like to update.
////// Updates a file /// Documentation: https://developers.google.com/bulldoze/v2/reference/files/update /// /// a Valid authenticated DriveService /// path to the file to upload /// Collection of parent folders which contain this file. /// Setting this field will put the file in all of the provided folders. root folder. /// the resource id for the file nosotros would like to update ///If upload succeeded returns the File resource of the uploaded file /// If the upload fails returns zippo public static File updateFile(DriveService _service, cord _uploadFile, string _parent,string _fileId) { if (System.IO.File.Exists(_uploadFile)) { File trunk = new File(); body.Title = System.IO.Path.GetFileName(_uploadFile); body.Description = "File updated past Diamto Drive Sample"; body.MimeType = GetMimeType(_uploadFile); body.Parents = new List() { new ParentReference() { Id = _parent } }; // File's content. byte[] byteArray = Organisation.IO.File.ReadAllBytes(_uploadFile); Organization.IO.MemoryStream stream = new System.IO.MemoryStream(byteArray); try { FilesResource.UpdateMediaUpload request = _service.Files.Update(body, _fileId, stream, GetMimeType(_uploadFile)); request.Upload(); render asking.ResponseBody; } catch (Exception e) { Panel.WriteLine("An fault occurred: " + e.Bulletin); return null; } } else { Console.WriteLine("File does not be: " + _uploadFile); return zilch; } }
Notice how this fourth dimension we employ service.files.update() and we get an FileRecources.UpdateMediaUpload back. You probably don't want to to loop though all of the files updating them all. It would probably make more sense to figure out exactly which file information technology is.
Patch
There is a second way to Update a file. If all you want to do is modify its meta information so you tin can utilize Patch.
File file = new File(); file.Championship = newTitle; // Rename the file. FilesResource.PatchRequest asking = service.Files.Patch(file, fileId); File updatedFile = request.Fetch();
This will only rename the file with out irresolute the continence of file itself.
Delete
Finally nosotros come to delete. Delete similar Update and upload requires the fileId. Use the same code equally we used to a higher place but instead of all the Metadata and stream stuff merely employ this
FilesResource.DeleteRequest DeleteRequest = service.Files.Delete(file.Id); DeleteRequest.Execute();
This will permanently delete the file with that id. It skips the trash.
Trash
Instead of permanently deleting a file you can simply trash it.
service.files().trash(fileId).execute();
You can too untrash a file
service.Files.Untrash(fileId).Fetch();
Trashing is probably better then deleting unless y'all ask the user if they are certain they desire to delete the file.
Concision
You should now understand how to access the Google Bulldoze API with an authenticated user. You should as well understand how to upload files to Google Bulldoze, how to update a file on Google Drive. We have also talked about the difference between deleting and trashing files from Google Drive. I hope yous will also agree that working with the Google APIs is quite piece of cake in one case you become the authentication down.
randolphwifforge53.blogspot.com
Source: https://www.daimto.com/google-drive-api-c-upload/
0 Response to "Google Drive Rest Api Upload File Another Account"
Post a Comment