Are you working on an application where you would like to upload a file to Google drive. There are some changes from google drive v2 to the new Google drive v3 and a lot of the samples out there for v2 wont work for the new Google drive API v3.
Setup
The first thing you will need to do is create a new project on Google developer console. For this project i will be using a console application so we will create a native client. Note this code will NOT work for a web browser application.
You will also need the NuGet package Install-Package Google.Apis.Drive.v3
Code
I am passing the Json file which I downloaded from the Google Developer console and passing it directly to the getDriveService method. MyUser is just a string used to denote the user that the credentials will be saved under. If your intersted in reading how this works you may want to read my Filedatastore tutorial after that we pass the scopes that we need.
We use a file stream to load the file and the upload method to preform the upload. This is a simple upload method and will work for files under 5mb.
var service = Oauth2Example.GetDriveService(@"C:\Users\lilaw\Documents\.credentials\NativeClient.json", "MyUser",
new[] {Google.Apis.Drive.v3.DriveService.Scope.Drive});
var fileMetadata = new Google.Apis.Drive.v3.Data.File()
{
Name = "flag.jpg"
};
FilesResource.CreateMediaUpload request;
using (var stream = new System.IO.FileStream(@"C:\temp\flag.jpg", System.IO.FileMode.Open))
{
request = service.Files.Create(fileMetadata, stream, "image/jpeg");
request.Fields = "id";
request.Upload();
}
var file = request.ResponseBody;
Console.WriteLine(file.Id);
Conclusion
Simple upload gives us a method for uploading small files to google drive. I would like to thank ChrisUK for being desprate enough that I finally got around to creating this tutorial.
I’m confused about something concerning Google Drive Api v3. This is a scenario I use now :
WinForm application project, VS2015
Two Forms
[Form1 to authenticate user to use my Google Drive Folder(ThisFolder)]
[Form2 to upload files to my google drive folder(ThisFolder)]
[Form1]
I use a native code to receive access Token [using loopback url] and save it to User settings file (My.Settings.accesstoken=received_access_token)
[Form2]
When I use your Example, it still opens web browser to authenticate user before uploading.
and uploading is done.
My problem is that I don’t want to re-authenticate the user each time the user tries to upload a file.
If your allowing them to upload to your drive account then you should be using a service account. Which wouldn’t request authorization.
Here is an example as well.