Upload document using Google Drive API in .Net

|
| By Webner

We will create a console application using .net and upload documents to google drive using Google Drive API V3.

Step 1: Enable Drive API

  1. Go to the Google API Console.
  2. Select a project.
  3. In the sidebar on the left, click on Library.
  4. In the displayed list of available APIs, click the Drive API and click Enable API.
  5. Click on Credentials in the left tab and download the client configuration and save credentials.json.

Step 2: Add the Google.Apis.Drive.v3 package

Open the NuGet Package Manager Console, and run the following command:
Install-Package Google.Apis.Drive.v3

Step 3: Create the example

  1. Place the downloaded credentials.json file into the visual studio project.
  2. In the program.cs file create the following code

using Google.Apis.Auth.OAuth2;
using Google.Apis.Drive.v3;
using Google.Apis.Drive.v3.Data;
using Google.Apis.Services;
using Google.Apis.Util.Store;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;
namespace SampleDocs
{
public class Program
{
static string[] Scopes = { DriveService.Scope.Drive };
static string ApplicationName = "Drive API .NET sample";
static void Main(string[] args)
{
UserCredential credential;
// Google authentication for installed application
using (var stream =
new FileStream("credentials.json", FileMode.Open, FileAccess.Read))
{
string credPath = "token.json";
credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
GoogleClientSecrets.Load(stream).Secrets,
Scopes,
"user",
CancellationToken.None,
new FileDataStore(credPath, true)).Result;
}
// Create Drive API service.
var service = new DriveService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = ApplicationName,
});
// File to be uploaded
string filePath = System.Web.Hosting.HostingEnvironment.MapPath(@"~\testing.docx");
var FileMetaData = new Google.Apis.Drive.v3.Data.File();
FileMetaData.Name = "testing";
// set mime type for file to be uploaded
FileMetaData.MimeType = MimeMapping.GetMimeMapping(filePath);
Google.Apis.Drive.v3.FilesResource.CreateMediaUpload request;
// Upload file in google drive
using (var stream = new System.IO.FileStream(filePath, System.IO.FileMode.Open))
{
request = service.Files.Create(FileMetaData, stream, MimeMapping.GetMimeMapping(filePath));
request.Fields = "id";
request.Upload();
}
string docId = request.ResponseBody.Id;
}
}
}

When we run this program it will take us to google authentication where we will give the login credentials for our google account and after that the file will be uploaded to google drive.

Leave a Reply

Your email address will not be published. Required fields are marked *