SHARE:

Google Drive API with .NET, an alternative to Azure Blob Storage

Google Drive REST API Overview

The Drive platform gives you a group of APIs along with client libraries, language-specific examples, and documentation to help you develop apps that integrate with Drive.

The core functionality of Drive apps is to download and upload files in Google Drive. However, the Drive platform provides a lot more than just storage, such as Create and open files, Search for files……

It’s a very interesting alternative to Azure Blob Storage, because Google offers you 15 GB free storage, but there is one limitation : 500.000 requests maximum per day.

.NET Quickstart

Complete the steps described in the rest of this page, and in about five minutes you’ll have a simple .NET console application that makes requests to the Drive API.

Prerequisites

To run this quickstart, you’ll need:

  • Visual Studio 2013 or later.
  • Access to the internet and a web browser.
  • A Google account with Google Drive enabled.

Step 1: Enable the Drive API 

  • Use this wizard
  •  to create or select a project in the Google Developers Console and automatically enable the API. Click the Go to credentials button to continue.

  • At the top of the page, select the OAuth consent screen tab. Select an Email address, enter a Product name if not already set, and click the Save button.

  • Back on the Credentials tab, click the Add credentials button and select OAuth 2.0 client ID.

  • Select the application type Other and click the Create button.

  • Click OK to dismiss the resulting dialog.

  • Click the  (Download JSON) button to the right of the client ID. Move this file to your working directory and rename it client_secret.json.

Step 2: Prepare the project

  • Create a new Visual C# Console Application project in Visual Studio.
  • Open the NuGet Package Manager Console, select the package source nuget.org, and run the following command:
     PM> Install-Package Google.Apis.Drive.v2

You may have this issue :

Your NuGet client version is not up to date, you have to donwload and install the lastest release here : https://nuget.codeplex.com/releases/view/118318

Step 3: Set up the sample

Drag client_secret.json (downloaded in Step 1) into your Visual Studio Solution Explorer.

Select client_secret.json, and then go to the Properties window and set the Copy to Output Directory field to Copy always.

Replace the contents of Program.cs with the following code:

using System;
using Google.Apis.Auth.OAuth2;
using Google.Apis.Drive.v2;
using Google.Apis.Services;
using Google.Apis.Util.Store;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Threading;
using File = Google.Apis.Drive.v2.Data.File;

namespace GoogleDriveAPI
{
    class Program
    {
        static string[] Scopes = { DriveService.Scope.Drive };
        static string ApplicationName = "GoogleDriveAPIDemoApp";

        static void Main(string[] args)
        {
            UserCredential credential;

            using (var stream =
                new FileStream("client_secret.json", FileMode.Open, FileAccess.Read))
            {
                string credPath = System.Environment.GetFolderPath(
                    System.Environment.SpecialFolder.Personal);
                credPath = Path.Combine(credPath, ".credentials/drive-dotnet-Demo");

                credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
                    GoogleClientSecrets.Load(stream).Secrets,
                    Scopes,
                    "user",
                    CancellationToken.None,
                    new FileDataStore(credPath, true)).Result;
                Console.WriteLine("Credential file saved to: " + credPath);
            }

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

            /////////////////////////////// UPLOAD FILE /////////////////////////////////////
            UploadFile(service);

            ////////////////////////////// LIST FILES //////////////////////////////////////
            ListFiles(service);
            

        }

        private static void UploadFile(DriveService service)
        {
            File body = new File();
            body.Title = "test upload";
            body.Description = "test upload";
            body.MimeType = "application/vnd.ms-excel";

            
            // File's content.
            byte[] byteArray = System.IO.File.ReadAllBytes("/Temp/testUploadExcel.xlsx");
            MemoryStream stream = new MemoryStream(byteArray);
            try {
                FilesResource.InsertMediaUpload request = service.Files.Insert(body, stream, "application/vnd.google-apps.spreadsheet");
                request.Upload();

              File file = request.ResponseBody;

              // Uncomment the following line to print the File ID.
              // Console.WriteLine("File ID: " + file.Id);

            } catch (Exception e) {
              Console.WriteLine("An error occurred: " + e.Message);
            }
        }

        
        private static void ListFiles(DriveService service)
        {
            // Define parameters of request.
            FilesResource.ListRequest listRequest = service.Files.List();
            listRequest.MaxResults = 100;

            // List files.
            IList files = listRequest.Execute()
                .Items;
            Console.WriteLine("Files:");
            if (files != null && files.Count > 0)
            {
                foreach (var file in files)
                {
                    Console.WriteLine("{0} ({1})", file.Title, file.Id);
                    Debug.WriteLine("{0} ({1})", file.Title, file.Id);
                }
            }
            else
            {
                Console.WriteLine("No files found.");
            }
            Console.Read();
        }
    }
}

Step 4: Upload a file :

When a file is uploaded, Google Drive API provides you in the upload result,the file Id, and its donwload url :

The uploaded file is also available on the Google Drive UI :

Step 5: List files:

That’s it! in a next article i will describe how to create Sheets (excel files), and manipulate it through Google Drive API and Google Sheet API 🙂

Written by

anthonygiretti

Anthony is a specialist in Web technologies (14 years of experience), in particular Microsoft .NET and learns the Cloud Azure platform. He has received twice the Microsoft MVP award and he is also certified Microsoft MCSD and Azure Fundamentals.
%d bloggers like this: