1
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

C#からGoogle Cloud Storageにアップロードする

Posted at

はじめに

C#でGoogle Cloud Storage(以下GCS)にアップロードする方法が乗った記事が古かったり、複数の記事に散在していたので一連の流れをまとめます。公式から情報を読み取って出来る人は公式に添ってやったほうが良いです(雰囲気知りたいだけの人は纏まってる方が良いよねと思ったのでこの記事書いてます)

GCSでバケットを作成する

以下のページに添って作成します。バケット名はあとで利用します。

サービスアカウントを作成する

以下のページに添って作成します。サービスアカウントキーは必ず作成してください。キー情報が含まれたJSONファイルはあとで利用します。

バケットの権限を有効にする

プリンシパルに先ほど作成したサービスアカウント名を入力します。ロールは「Storage オブジェクト管理者」を指定します※ロールに関しては用途に合わせて設定してください。
image.png

この作業を行わないと権限がなくアップロードした際に403エラーになります。

.NETプロジェクトを作成する

今回はconsoleアプリで作成します。

dotnet new console

GCPクライアントライブラリをインストールします

dotnet add package Google.Cloud.Storage.V1

サービスアカウントのキーファイルをビルド時にファイルコピーする

.NETプロジェクトを作成するで作成したcsprojファイルにサービスアカウントの作成で生成したキーファイル(JSON)を設定します。JSONはプロジェクトファイルと同じ位置に配置してください。

<ItemGroup>
  <None Update="wide-memento-xxxxxxx.json">
    <CopyToOutputDirectory>Always</CopyToOutputDirectory>
  </None>
</ItemGroup>

ファイルをアップロードする

いきなり雑になってしまいましたが、以下の通りにプログラムを作成します。環境変数を設定しないとアップロード出来ないのでSetEnvironmentVariableは必ず設定してください。PCで環境変数を設定している場合は不要です。

※サンプルは最上位レベルのステートメントのテンプレートを利用しています。慣れない人はdotnet new console --use-program-mainを使って生成してください

// See https://aka.ms/new-console-template for more information
using Google.Cloud.Storage.V1;

// 環境変数を設定する
// ref. https://cloud.google.com/docs/authentication/getting-started?hl=ja#setting_the_environment_variable
Environment.SetEnvironmentVariable(
            "GOOGLE_APPLICATION_CREDENTIALS",
            Path.Combine(AppContext.BaseDirectory, "wide-memento-xxxxxxxxx.json"));

// ローカルファイルのパス
var localPath = "";
// バケット名
var bucketName = "";
// ファイル名
var fileName = "";
var storage = StorageClient.Create();
using var fileStream = File.OpenRead(localPath);
storage.UploadObject(bucketName, fileName, null, fileStream);

サンプルは以下に置いています

さいごに

意外にも一連の流れでGCSを利用する方法を述べている記事が少なかったのでまとめてみました。今更感ある内容でしたが誰かのご参考になれば幸いです。

参考

https://cloud.google.com/docs/authentication/getting-started?hl=ja
https://learn.microsoft.com/ja-jp/dotnet/api/system.environment.setenvironmentvariable?view=net-7.0
https://cloud.google.com/storage/docs/uploading-objects?hl=ja

1
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?