Skip to content

Instantly share code, notes, and snippets.

@andreymir
Created August 28, 2013 21:10
Show Gist options
  • Select an option

  • Save andreymir/6371343 to your computer and use it in GitHub Desktop.

Select an option

Save andreymir/6371343 to your computer and use it in GitHub Desktop.
Upload a file to google drive using service account.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography.X509Certificates;
using System.Web;
using System.Web.Mvc;
using DotNetOpenAuth.OAuth2;
using Google.Apis.Authentication;
using Google.Apis.Authentication.OAuth2.DotNetOpenAuth;
using Google.Apis.Drive.v2;
using Google.Apis.Util;
using Google.Apis.Authentication.OAuth2;
using Google.Apis.Services;
using Google.Apis.Drive.v2.Data;
namespace GoogleDriveSample.Controllers
{
public class UploadController : Controller
{
private const string SERVICE_ACCOUNT_EMAIL = "****************@developer.gserviceaccount.com";
//
// GET: /Upload/
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult UploadFile(HttpPostedFileBase file)
{
using (var service = BuildService())
{
var gFile = new File { Title = "GoogleDriveSample.png" };
var request = service.Files.Insert(gFile, file.InputStream, file.ContentType);
request.Upload();
gFile = request.ResponseBody;
}
return RedirectToAction("Success");
}
public ActionResult Success()
{
return View();
}
/// <summary>
/// Build a Drive service object authorized with the service account.
/// </summary>
/// <returns>Drive service object.</returns>
private DriveService BuildService()
{
var certificate = new X509Certificate2(Server.MapPath("~/App_Data/**********************************-privatekey.p12"), "notasecret",
X509KeyStorageFlags.Exportable);
var provider = new AssertionFlowClient(GoogleAuthenticationServer.Description, certificate)
{
ServiceAccountId = SERVICE_ACCOUNT_EMAIL,
Scope = DriveService.Scopes.Drive.GetStringValue(),
};
var auth = new OAuth2Authenticator<AssertionFlowClient>(provider, AssertionFlowClient.GetState);
return new DriveService((new BaseClientService.Initializer()
{
Authenticator = auth,
ApplicationName = "Drive API Sample",
}));
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment