12

Is there any code example of a desktop application how to authorize to Google Drive service and upload a file?

Currently I have:

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

But what are the next steps? As I see from examples I should get IAuthenticator instance and pass it into constructor of DriveService class... How to get an instance of IAuthenticator? If my above code is correct... Thanks in advance.

Hogan
  • 7,224
  • 2
  • 22
  • 15
Alexey
  • 1,826
  • 3
  • 17
  • 20

1 Answers1

19

Here is a complete command-line sample in C# to upload a file to 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);
        }
    }
}

UPDATE: this quickstart sample is now available at https://developers.google.com/drive/quickstart

Claudio Cherubino
  • 14,896
  • 1
  • 35
  • 42
  • 1
    I know it is a bit old post. But I tried using your code for learning purpose. But I am afraid I am getting compilation error in `var service = new DriveService(auth);`. The compilation error shows as `Argument 1: cannot convert from 'Google.Apis.Authentication.OAuth2.OAuth2Authenticator' to 'Google.Apis.Services.BaseClientService.Initializer'.` Can you help with this? – Sandy Mar 28 '13 at 09:21
  • Moreover I am a bit confused with few more concepts and cant get them in my head even after reading on internet. I have seen your SO profile, 0 questions and above 400 answers. I would be great full if I can take your 5 minutes on SO chat to clarify few of my confusions. I know I am asking too much now :) – Sandy Mar 28 '13 at 09:23
  • So I fixed it, I was using a wrong version of dll. Now have to work to erase my other confusions – Sandy Mar 28 '13 at 09:47
  • @Claudio Cherubino : Can it be integrated in visual studio 2008 – DSP Jun 17 '17 at 09:16
  • More recent (v3): https://developers.google.com/drive/api/v3/quickstart/dotnet – Pedro Reis Oct 10 '20 at 22:14