2012-08-16 10 views
11

¿Hay algún ejemplo de código de una aplicación de escritorio sobre cómo autorizar al servicio de Google Drive y cargar un archivo?C# Aplicación de escritorio. Ejemplo simple de cómo cargar un archivo en Google Drive

Actualmente tengo:

var parameters = new OAuth2Parameters 
           { 
            ClientId = ClientCredentials.ClientId, 
            ClientSecret = ClientCredentials.ClientSecret, 
            RedirectUri = ClientCredentials.RedirectUris[0], 
            Scope = ClientCredentials.GetScopes() 
           };  
string url = OAuthUtil.CreateOAuth2AuthorizationUrl(parameters); 
    // Open url, click to allow and copy secret code 
    parameters.AccessCode = secretCodeFromBrowser; 
    OAuthUtil.GetAccessToken(parameters); 
    string accessToken = parameters.AccessToken; 
    // So, there is the access token 

Pero ¿cuáles son los siguientes pasos? Como veo en los ejemplos, debería obtener la instancia IAuthenticator y pasarla al constructor de la clase DriveService ... ¿Cómo obtener una instancia de IAuthenticator? Si mi código anterior es correcto ... Gracias de antemano.

+0

duplicado posible: http: // stackoverflow .com/questions/10317638/inserting-file-to-google-drive-through-api –

+0

Para cualquier persona que le gusta mantenerlo simple, escribí un contenedor simple que admite una API apta para los comandos de unidad. [Github Repo] (https://github.com/Berkays/Drive.Net) – Berkays

Respuesta

19

Este es un ejemplo de línea de comandos completa en C# para cargar un archivo en Google Drive:

using System; 
using System.Diagnostics; 
using DotNetOpenAuth.OAuth2; 
using Google.Apis.Authentication.OAuth2; 
using Google.Apis.Authentication.OAuth2.DotNetOpenAuth; 
using Google.Apis.Drive.v2; 
using Google.Apis.Drive.v2.Data; 
using Google.Apis.Util; 

namespace GoogleDriveSamples 
{ 
    class DriveCommandLineSample 
    { 
     static void Main(string[] args) 
     { 
      String CLIENT_ID = "YOUR_CLIENT_ID"; 
      String CLIENT_SECRET = "YOUR_CLIENT_SECRET"; 

      // Register the authenticator and create the service 
      var provider = new NativeApplicationClient(GoogleAuthenticationServer.Description, CLIENT_ID, CLIENT_SECRET); 
      var auth = new OAuth2Authenticator<NativeApplicationClient>(provider, GetAuthorization); 
      { 
       Authenticator = auth 
      }); 

      File body = new 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(); 

      File file = request.ResponseBody; 
      Console.WriteLine("File id: " + file.Id); 
      Console.ReadLine(); 
     } 

     private static IAuthorizationState GetAuthorization(NativeApplicationClient arg) 
     { 
      // Get the auth URL: 
      IAuthorizationState state = new AuthorizationState(new[] { DriveService.Scopes.Drive.GetStringValue() }); 
      state.Callback = new Uri(NativeApplicationClient.OutOfBandCallbackUrl); 
      Uri authUri = arg.RequestUserAuthorization(state); 

      // Request authorization from the user (by opening a browser window): 
      Process.Start(authUri.ToString()); 
      Console.Write(" Authorization Code: "); 
      string authCode = Console.ReadLine(); 
      Console.WriteLine(); 

      // Retrieve the access token by using the authorization code: 
      return arg.ProcessUserAuthorization(authCode, state); 
     } 
    } 
} 

ACTUALIZACIÓN: este ejemplo rápidos ya está disponible en https://developers.google.com/drive/quickstart

+1

Sé que es un post un poco viejo. Pero traté de usar tu código con fines de aprendizaje. Pero me temo que estoy obteniendo un error de compilación en 'var service = new DriveService (auth);'. El error de compilación se muestra como 'Argumento 1: no se puede convertir de' Google.Apis.Authentication.OAuth2.OAuth2Authenticator 'a' Google.Apis.Services.BaseClientService.Initializer'. ¿Me puedes ayudar con esto? – Sandy

+0

Además, estoy un poco confundido con algunos conceptos más y no puedo tenerlos en mi cabeza, incluso después de leer en Internet. He visto su perfil SO, 0 preguntas y más de 400 respuestas. Estaría genial si puedo tomar tus 5 minutos en el chat SO para aclarar algunas de mis confusiones. Sé que estoy pidiendo demasiado ahora :) – Sandy

+0

Así que lo arreglé, estaba usando una versión incorrecta de dll. Ahora tengo que trabajar para borrar mis otras confusiones – Sandy

Cuestiones relacionadas