Subir un archivo en Drive mediante Google Api y OAuth

Fuente: https://developers.google.com/drive/web/quickstart/quickstart-cs


1. Ir a la consola de desarrollo de google y crear un nuevo proyecto
https://console.developers.google.com/project

2. Click en el proyecto creado

3. Abrir APIs y seleccionar el api a utilizar (en este caso Drive API)

4. Clickear en Habilitar API

5. Crear un ID de cliente nuevo (ir a Credenciales, Crear ID de cliente nuevo, y elegir "Aplicacion Instalada", y Otros

6. Luego que lo crea, presionar el boton "Descargar JSON", y guardar el archivo en la ruta Debug de la aplicacion que vamos a crear mas abajo, con el nombre client_secrets.json

7. Crear un archivo document.txt y guardarlo en el path Debug de la aplicacion.

8. Definir los campos usuario, password y dominio en NetworkCredential (estas son las credenciales del servidor proxy, si hay)

9. Crear la aplicacion de consola y ejecutarla, se va a abrir un browser pidiendo autorizacion para acceder a Drive. Si por defecto se abre el Internet Explorer, copiar la url, pegarla en Chrome y aceptar allí.

10. Ir a Drive y verificar que se haya subido el archivo (con nombre My document)

[Agregar las referencias mediante NuGet, de Google.Apis y Drive]

using System;
using System.IO;
using System.Threading;
using Google.Apis.Auth.OAuth2;
using Google.Apis.Drive.v2;
using Google.Apis.Services;
using Google.Apis.Util.Store;
using System.Net;

namespace Drive3
{
    class DriveCommandLineSample
    {
        static void Main(string[] args)
        {
            UserCredential credential;

            HttpWebRequest webRequest = WebRequest.Create(@"http://www.google.com") as HttpWebRequest;
            webRequest.Proxy = WebRequest.DefaultWebProxy;
            webRequest.Credentials = new NetworkCredential([UsuarioProxy], [PasswordProxy], [DominioProxy]);
            webRequest.Proxy.Credentials = new NetworkCredential([UsuarioProxy], [PasswordProxy], [DominioProxy]);

            using (var filestream = new FileStream("client_secrets.json",
                FileMode.Open, FileAccess.Read))
            {
                credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
                    GoogleClientSecrets.Load(filestream).Secrets,
                    new[] { DriveService.Scope.Drive },
                    "user",
                    CancellationToken.None,
                    new FileDataStore("DriveCommandLineSample")).Result;
            }

            // Create the service.
            var service = new DriveService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName = "Drive API Sample",
            });

            Google.Apis.Drive.v2.Data.File body = new Google.Apis.Drive.v2.Data.File();
            body.Title = "My document";
            body.Description = "A test document";
            body.MimeType = "text/plain";

            byte[] byteArray = System.IO.File.ReadAllBytes("document.txt");
            System.IO.MemoryStream stream = new System.IO.MemoryStream(byteArray);

            FilesResource.InsertMediaUpload request = service.Files.Insert(body, stream, "text/plain");
            request.Upload();

            Google.Apis.Drive.v2.Data.File file = request.ResponseBody;
            Console.WriteLine("File id: " + file.Id);
            Console.WriteLine("Press Enter to end this process.");
            Console.ReadLine();

        }
    }
}

No hay comentarios:

Publicar un comentario