My Blog

Google drive file management in .NET

by lupok on venerdì 18 ottobre 2013 15:51
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;
using Google.Apis.Services;
using Google.Apis.Download;
using System.Security.Cryptography.X509Certificates;
using Google.Apis.Upload;
using Google.Apis.Samples.Helper;
using System.Collections.Generic;
 
namespace GoogleDriveUploadFile
{
   class Program
   {
      private const String CLIENT_ID = ".apps.googleusercontent.com";
      private const String CLIENT_SECRET = "";
 
      private const String STORAGE = "";
      private const String KEY = "";
 
      private const String FILE_NAME = "document.txt";
      private const String DOWNLOAD_FOLDER_NAME = "download";
      private const String FILE_TITLE = "GoogleDriverTestDocument";
      private const String MIME_TYPE = "text/plain";
      private const String FILE_DESCRIPTION = "Google drive test file";
 
      private const String FOLDER_NAME = "GoogleDriveTestFolder";
 
      static void Main(string[] args)
      {
         using (System.IO.StreamWriter sw = new System.IO.StreamWriter(FILE_NAME, false))
         {
            sw.WriteLine(DateTime.Now.ToString());
         }
 
         byte[] byteArray = System.IO.File.ReadAllBytes(FILE_NAME);
         System.IO.MemoryStream stream = new System.IO.MemoryStream(byteArray);
 
         var provider = new NativeApplicationClient(GoogleAuthenticationServer.Description, CLIENT_ID, CLIENT_SECRET);
         var auth = new OAuth2Authenticator<NativeApplicationClient>(provider, getAuthorization);
         var service = new DriveService(new BaseClientService.Initializer()
         {
            Authenticator = auth
         });
 
         File folder = searchFolder(service, FOLDER_NAME);
 
         if (folder == null)
            folder = createFolder(service, FOLDER_NAME);
 
 
         File uploadFile = retrieveFile(service, FILE_TITLE, folder);
 
         if (uploadFile == null)
         {
            File file = insertNewFile(FILE_TITLE, MIME_TYPE, FILE_DESCRIPTION, stream, service, folder);
 
            Console.WriteLine("Insert file id: " + file.Id);
            Console.WriteLine("Insert file contents: {0}", System.IO.File.ReadAllText(FILE_NAME));
         }
         else
         {
            File file = updateFile(stream, service, uploadFile);
 
            Console.WriteLine("Update file id: " + file.Id);
            Console.WriteLine("Update file contents: {0}", System.IO.File.ReadAllText(FILE_NAME));
         }
 
         File fileToDownload = retrieveFile(service, FILE_TITLE, folder);
         if (fileToDownload != null)
         {
            if (!System.IO.Directory.Exists(DOWNLOAD_FOLDER_NAME))
               System.IO.Directory.CreateDirectory(DOWNLOAD_FOLDER_NAME);
 
            String downloadFilename = System.IO.Path.Combine(DOWNLOAD_FOLDER_NAME, FILE_NAME);
 
            downloadFile(service, fileToDownload, downloadFilename);
 
            Console.WriteLine(downloadFilename + " was downloaded successfully");
            Console.WriteLine("Download file contents: {0}", System.IO.File.ReadAllText(downloadFilename));
         }
 
         Console.WriteLine("Press \"Enter\" to exit");
         Console.ReadLine();
      }
 
      // https://developers.google.com/drive/v2/reference/files/update
      private static File updateFile(System.IO.MemoryStream stream, DriveService service, File uploadFile)
      {
         FilesResource.UpdateMediaUpload request = service.Files.Update(uploadFile, uploadFile.Id, stream, MIME_TYPE);
 
         request.NewRevision = false;
 
         request.Upload();
 
         File file = request.ResponseBody;
 
         return file;
      }
 
      private static void downloadFile(DriveService service, File fileToDownload, String fileName)
      {
         var downloader = new Google.Apis.Download.MediaDownloader(service);
 
         using (var fileStream =
            new System.IO.FileStream(fileName, System.IO.FileMode.Create, System.IO.FileAccess.Write))
         {
            var progress = downloader.Download(fileToDownload.DownloadUrl, fileStream);
            if (progress.Status != DownloadStatus.Completed)
               throw new Exception(String.Format("Download file: {0} failed", fileToDownload.Title));
         }
      }
 
      // https://developers.google.com/drive/v2/reference/files/insert
      private static File insertNewFile(String title, String mimeType, String fileDescription,
         System.IO.MemoryStream stream, DriveService service, File folder)
      {
 
         List<ParentReference> parents = new List<ParentReference>() { new ParentReference() { Id = folder.Id } };
 
         File insertFile = new File()
         {
            Title = title,
            Parents = parents,
            Description = fileDescription,
            MimeType = mimeType
         };
 
         FilesResource.InsertMediaUpload request = service.Files.Insert(insertFile, stream, mimeType);
         IUploadProgress uploadProgress = request.Upload();
 
         if (uploadProgress.Status != UploadStatus.Completed)
            throw new Exception(String.Format("Upload file: {0} failed", title));
 
         return insertFile;
      }
 
      public static File retrieveFile(DriveService service, String title, File folder)
      {
         ChildrenResource.ListRequest request = service.Children.List(folder.Id);
 
         ChildList files = request.Execute();
 
         foreach (ChildReference child in files.Items)
         {
            File file = service.Files.Get(child.Id).Execute();
 
            if (file.Title == title)
               return file;
         }
 
         return null;
      }
 
      private static IAuthorizationState getAuthorization(NativeApplicationClient client)
      {
         string[] scopes = new[] { DriveService.Scopes.DriveFile.GetStringValue(), DriveService.Scopes.Drive.GetStringValue() };
 
         IAuthorizationState state = AuthorizationMgr.GetCachedRefreshToken(STORAGE, KEY);
         if (state != null)
         {
            client.RefreshToken(state);
            return state;
         }
 
         state = AuthorizationMgr.RequestNativeAuthorization(client, scopes);
         AuthorizationMgr.SetCachedRefreshToken(STORAGE, KEY, state);
         return state;
      }
 
      private static ChildReference insertFileIntoFolder(DriveService service, String folderId, String fileId)
      {
         ChildReference newChild = new ChildReference();
 
         newChild.Id = fileId;
 
         return service.Children.Insert(newChild, folderId).Execute(); ;
      }
 
      private static File searchFolder(DriveService service, string folderTitle)
      {
         FilesResource.ListRequest request = service.Files.List();
         request.Q = "mimeType='application/vnd.google-apps.folder' and trashed=false";
         FileList files = request.Execute();
 
         foreach (File item in files.Items)
         {
            if (item.Title == folderTitle)
               return item;
         }
 
         return null;
      }
 
      private static File createFolder(DriveService service, string folderTitle)
      {
 
         File body = new File() { Title = folderTitle, MimeType = "application/vnd.google-apps.folder" };
 
         File newFolder = service.Files.Insert(body).Execute();
 
         return newFolder;
      }
   }
}

GoogleDriveUploadFile.zip

Blogs Parent Separator My Blog
Author
lupok

My Blog

Tags