[C#] Upload to Google Drive

  • 3316
  • 0
  • 2018-07-31

Upload to Google Drive 

Environment: Microsoft Visual Studio Enterprise 2015
 

1. Get ClientId, ClientSecret

1.1 Go to https://console.developers.google.com/apis/library

1.2 Click Google Drive API

1.3 Active 

1.4 Credential(憑證)

1.5 建立憑證 > OAuth用戶端ID

1.6 設定同意畫面

1.7 Input 向使用者顯示的產品名稱 > 儲存

1.8 其他 > Input 名稱 > 建立

1.9 Get ClientId, ClientSecret

 

2. Nuget Google APIs

 

3. Coding

https://www.daimto.com/google-drive-api-c-upload/

using Google.Apis.Auth.OAuth2;
using Google.Apis.Drive.v3;
using Google.Apis.Drive.v3.Data;
using Google.Apis.Services;
using Google.Apis.Util.Store;
using System;
using System.Threading;

namespace GoogleDrive
{
    static class Program
    {
        [STAThread]
        static void Main()
        {
            UserCredential credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
                new ClientSecrets { ClientId = "ClientId", ClientSecret = "ClientSecret" },
                new[] { DriveService.Scope.Drive, DriveService.Scope.DriveFile },
                "QuantaClient",
                CancellationToken.None,
                new FileDataStore("Drive.Auth.Store")).Result;

            var service = new DriveService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName = "QuantaShopFloor",
            });


            File body = updateFile(service, @"_uploadFile", "_fileId");

        }

        public static File updateFile(DriveService _service, string _uploadFile, string _fileId)
        {

            if (System.IO.File.Exists(_uploadFile))
            {
                File body = new File();
                body.Name = System.IO.Path.GetFileName(_uploadFile);
                body.Description = "File updated by Diamto Drive Sample";
                body.MimeType = GetMimeType(_uploadFile);

                byte[] byteArray = System.IO.File.ReadAllBytes(_uploadFile);
                System.IO.MemoryStream stream = new System.IO.MemoryStream(byteArray);
                try
                {
                    FilesResource.UpdateMediaUpload request = _service.Files.Update(body, _fileId, stream, GetMimeType(_uploadFile));
                    request.Upload();
                    return request.ResponseBody;
                }
                catch (Exception e)
                {
                    Console.WriteLine("An error occurred: " + e.Message);
                    return null;
                }
            }
            else
            {
                Console.WriteLine("File does not exist: " + _uploadFile);
                return null;
            }

        }

        private static string GetMimeType(string fileName)
        {
            string mimeType = "application/unknown";
            string ext = System.IO.Path.GetExtension(fileName).ToLower();
            Microsoft.Win32.RegistryKey regKey = Microsoft.Win32.Registry.ClassesRoot.OpenSubKey(ext);
            if (regKey != null && regKey.GetValue("Content Type") != null)
                mimeType = regKey.GetValue("Content Type").ToString();
            return mimeType;
        }

    }
}