Google Driveにファイルをアップロードする - C#

C#のプログラムでGoogle Driveにファイルをアップロードするコードを紹介します。

事前準備

Google Drive API の有効化

Google Drive APIを有効化します。手順はこちらの記事を参照してください。

Google APIのサービスアカウントを作成

Google APIのサービスアカウントを作成します。アカウントの作成手順はこちらの記事 を参照してください。

Google API サービスアカウントの認証キーを作成

Google API サービスアカウントの認証キーを作成します。 作成の具体的な手順はこちらの記事を参照してください。
今回はJSON形式のキーファイルを作成しています。

Google Driveの準備

Google Drive にログインし共有フォルダを作成し、先の手順で作成したサービスアカウントと共有します。
具体的な操作手順はこちらの記事を参照して下さい。

C#プロジェクトの作成

C#のプロジェクトを作成します。今回はWindows Formアプリケーションを作成します。
作成したプロジェクトに Google.Apis.Drive.V3 パッケージをインストールします。 インストールの手順はこちらの記事を参照してください。

プログラム

UI

下図のフォームを作成します。1行のテキストボックスを2つ、複数行のテキストボックスを1つ、ボタンを2つ、OpenFileDialog を配置します。

コード

下記のコードを記述します。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Google.Apis.Drive.v3;
using System.IO;


namespace GoogleDriveUpload
{
  public partial class FormSimpleFileUplopad : Form
  {
    public FormSimpleFileUplopad()
    {
      InitializeComponent();
    }

    static string[] Scopes = { DriveService.Scope.Drive };

    private void button1_Click(object sender, EventArgs e)
    {
      if (openFileDialog1.ShowDialog() == DialogResult.OK) {
        textBox1.Text = openFileDialog1.FileName;
      }
    }

    private void button2_Click(object sender, EventArgs e)
    {
      FileStream fs = new FileStream("ipentectest-854e0153b985.json", FileMode.Open, FileAccess.Read);
      Google.Apis.Auth.OAuth2.GoogleCredential credential;
      try {
        credential = Google.Apis.Auth.OAuth2.GoogleCredential.FromStream(fs).CreateScoped(Scopes);
      }
      finally {
        fs.Close();
      }

      Google.Apis.Services.BaseClientService.Initializer init = new Google.Apis.Services.BaseClientService.Initializer();
      init.HttpClientInitializer = credential;
      init.ApplicationName = "My Test App";
      DriveService service = new DriveService(init);


      Google.Apis.Upload.IUploadProgress prog;
      FileStream fsu = new FileStream(textBox1.Text, FileMode.Open);
      try {
        Microsoft.AspNetCore.StaticFiles.FileExtensionContentTypeProvider fpv = new Microsoft.AspNetCore.StaticFiles.FileExtensionContentTypeProvider();
        string ContentType;
        fpv.TryGetContentType(textBox1.Text, out ContentType);

        Google.Apis.Drive.v3.Data.File meta = new Google.Apis.Drive.v3.Data.File();
        meta.Name = Path.GetFileName(textBox1.Text);
        meta.MimeType = ContentType;
        meta.Parents = new List<string>() { textBox2.Text };

        Google.Apis.Drive.v3.FilesResource.CreateMediaUpload req = service.Files.Create(meta, fsu, ContentType);
        req.Fields = "id, name";
        prog = req.Upload();
      }
      finally {
        fsu.Close();
      }

      textBox3.Text = string.Format("アップロードが完了しました。{0:d}byte", prog.BytesSent);
    }
  }
}

解説

[button1]はファイルを参照するための処理です。OpenDialogを開き、選択されたファイルのフルパスを textBox1 に設定します。
    private void button1_Click(object sender, EventArgs e)
    {
      if (openFileDialog1.ShowDialog() == DialogResult.OK) {
        textBox1.Text = openFileDialog1.FileName;
      }
    }

[button2] がファイルのアップロードの処理です。 最初の部分は認証とGoogle Driveのサービスオブジェクトを作成する処理です。 コードの詳細はこちらの記事を参照してください。
  FileStream fs = new FileStream("ipentectest-854e0153b985.json", FileMode.Open, FileAccess.Read);
  Google.Apis.Auth.OAuth2.GoogleCredential credential;
  try {
    credential = Google.Apis.Auth.OAuth2.GoogleCredential.FromStream(fs).CreateScoped(Scopes);
  }
  finally {
    fs.Close();
  }

  Google.Apis.Services.BaseClientService.Initializer init = new Google.Apis.Services.BaseClientService.Initializer();
  init.HttpClientInitializer = credential;
  init.ApplicationName = "My Test App";
  DriveService service = new DriveService(init);

アップロードするファイルを読み込む FileStream オブジェクトを作成します。
  FileStream fsu = new FileStream(textBox1.Text, FileMode.Open);

アップロードするファイルのMime ContentTypeを取得します。今回は.NET 5のWindows Formアプリケーションプロジェクトのため、Microsoft.AspNetCore.StaticFiles.FileExtensionContentTypeProvider を利用しています。.NET Framework 4.8のWindows Formアプリケーションの場合は、 System.Web.MimeMapping.GetMimeMapping() メソッドを利用できます。
  Microsoft.AspNetCore.StaticFiles.FileExtensionContentTypeProvider fpv = new Microsoft.AspNetCore.StaticFiles.FileExtensionContentTypeProvider();
  string ContentType;
  fpv.TryGetContentType(textBox1.Text, out ContentType);

アップロードするファイルの File オブジェクトを作成します。 Nameにアップロード先のファイル名を設定します。今回は Path.GetFileName() メソッドを利用してアップロードするファイル名と同じファイルに設定します。 MimeTypeには先ほどの処理で求めた拡張子に対応したMimeTypeを設定します。 ParentsはファイルをアップロードするフォルダのIDを設定します。
  Google.Apis.Drive.v3.Data.File meta = new Google.Apis.Drive.v3.Data.File();
  meta.Name = Path.GetFileName(textBox1.Text);
  meta.MimeType = ContentType;
  meta.Parents = new List<string>() { textBox2.Text };

ファイルを作成し、Uploadメソッドを呼び出しファイルをアップロードします。
アップロードするファイル情報のFileオブジェクトを第一引数に、アップロードするファイルのFileStreamはCreateメソッドの第二引数に与えます。
  Google.Apis.Drive.v3.FilesResource.CreateMediaUpload req = service.Files.Create(meta, fsu, ContentType);
  req.Fields = "id, name";
  prog = req.Upload();
}
finally {
  fsu.Close();
}

テキストボックスにアップロードが完了した旨のメッセージと転送したバイト数を表示します。
textBox3.Text = string.Format("アップロードが完了しました。{0:d}byte", prog.BytesSent);

実行結果

アップロード先のGoogle Driveのフォルダーを確認します。ファイルが3つ配置されています。


アップロードするファイルを確認します。


上記のプロジェクトを実行します。下図のウィンドウが表示されます。


アップロードするファイルとアップロード先のフォルダのIDを入力します。入力後[button2]ボタンをクリックします。


ボタンをクリックするとファイルのアップロードが実行されます。アップロードが完了すると、下図のメッセージが表示されます。


アップロード先のGoogle Driveのフォルダーを確認します。ファイルが一つ増えており、アップロードしたファイルが追加されていることが確認できます。


補足

Upload() メソッドは同期メソッドのため、ファイルのアップロード中は制御が戻りませんのでUIがロックされた状態になります。 そのため、アップロードするファイルサイズが大きい場合はUIがフリーズしないようにするために、 非同期アップロード処理である、UploadAsync() メソッドを利用します。
コード例
   private async void button3_Click(object sender, EventArgs e)
    {
      FileStream fs = new FileStream("(JSONキーファイルのパス)", FileMode.Open, FileAccess.Read);
      Google.Apis.Auth.OAuth2.GoogleCredential credential;
      try {
        credential = Google.Apis.Auth.OAuth2.GoogleCredential.FromStream(fs).CreateScoped(Scopes);
      }
      finally {
        fs.Close();
      }

      Google.Apis.Services.BaseClientService.Initializer init = new Google.Apis.Services.BaseClientService.Initializer();
      init.HttpClientInitializer = credential;
      init.ApplicationName = "My Test App";
      DriveService service = new DriveService(init);


      Google.Apis.Upload.IUploadProgress prog;
      FileStream fsu = new FileStream(textBox1.Text, FileMode.Open);
      try {
        Microsoft.AspNetCore.StaticFiles.FileExtensionContentTypeProvider fpv = new Microsoft.AspNetCore.StaticFiles.FileExtensionContentTypeProvider();
        string ContentType;
        fpv.TryGetContentType(textBox1.Text, out ContentType);

        Google.Apis.Drive.v3.Data.File meta = new Google.Apis.Drive.v3.Data.File();
        meta.Name = Path.GetFileName(textBox1.Text);
        meta.MimeType = ContentType;
        meta.Parents = new List<string>() { textBox2.Text };

        Google.Apis.Drive.v3.FilesResource.CreateMediaUpload req = service.Files.Create(meta, fsu, ContentType);
        req.Fields = "id, name";
        prog = await req.UploadAsync();
      }
      finally {
        fsu.Close();
      }

      textBox3.Text = string.Format("アップロードが完了しました。{0:d}byte", prog.BytesSent);
    }
このページのキーワード
  • Google Drive C# アップロード
  • Google Drive C# ファイル アップロード
著者
iPentecのメインプログラマー
C#, ASP.NET の開発がメイン、少し前まではDelphiを愛用
最終更新日: 2022-12-14
作成日: 2021-07-29
iPentec all rights reserverd.