0
1

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#] Azure.Storage.Blobsでファイル操作

Posted at

C#でAzure.Storage.Blobsを使い、ストレージアカウントに作成済みのコンテナに対して、

  • ファイルのダウンロード
  • ファイルのアップロード
  • ファイルの削除

する処理を書いたので、備忘録として。

環境

  • フレームワーク:.NET Framework 4.8
  • Nugetパッケージ
    • Azure.Storage.Blobs v12.19.1

コード全体

using Azure.Storage.Blobs;
using Azure.Storage.Blobs.Models;
using System;
using System.IO;
using System.Threading.Tasks;

namespace MyApp.Utils
{
    public class StorageAccountHelper
    {
        private static string connectionString = "接続文字列";
        private static string blobContainerName = "コンテナ名";

        // 渡されたbloblNameへのアクセスを行うBlobClientを作成する
        private static BlobClient CreateBlobClient(string blobName)
        {
            return new BlobClient(connectionString, blobContainerName, blobName);
        }
        
        // ファイルダウンロード
        public static async Task<FileInfo> DownloadAsync(string fileName)
        {
            BlobClient blobClient = CreateBlobClient(fileName);
            
            // ファイル名が一致するものがあるかどうかを確認
            Azure.Response<bool> isBlobExists = await blobClient.ExistsAsync();
            if (!isBlobExists.Value)
            {
                throw new Exception("ファイルが見つかりません。");
            }

            // ファイルをダウンロードする
            Azure.Response<BlobDownloadResult> blobDownloadResult = await blobClient.DownloadContentAsync();
            if (blobDownloadResult.GetRawResponse().IsError)
            {
                throw new Exception("ファイルのダウンロードに失敗しました。");
            }

            // ファイルのデータを取り出して返す
            FileInfo fileInfo = new FileInfo();
            fileInfo.content = blobDownloadResult.Value.Content.ToArray();
            fileInfo.contentType = blobDownloadResult.Value.Details.ContentType;
            return fileInfo;
        }

        // ファイルアップロード
        public static async Task UploadAsync(MemoryStream fileStream, string fileName)
        {
            BlobClient blobClient = CreateBlobClient(fileName);
            BlobHttpHeaders blobHttpHeaders = new BlobHttpHeaders() {
                ContentType = GetContentType(fileName)
            };
            // !ATTENTION! 同名のファイルがあった場合、上書きする処理です。
            await blobClient.UploadAsync(fileStream, blobHttpHeaders);
        }

        // ファイルの拡張子を元にMIMEタイプを返す
        private static string GetContentType(string filename)
        {
            switch (Path.GetExtension(filename).ToLower())
            {
                // Text
                case ".txt":
                    return "text/plain";
                // Image
                case ".pdf":
                    return "application/pdf";
                case ".jpg":
                case ".jpeg":
                    return "image/jpeg";
                case ".png":
                    return "image/png";
                // Zip
                case ".zip":
                    return "application/zip";
                // Others
                default:
                    return "";
            }
        }

        // ファイル削除
        public static async Task DeleteAsync(string fileName)
        {
            BlobClient blobClient = CreateBlobClient(fileName);
            
            // ファイル名が一致するものがあるかどうかを確認
            Azure.Response<bool> isBlobExists = await blobClient.ExistsAsync();
            if (isBlobExists.Value)
            {
                // ファイルがある場合のみ削除を行う
                await blobClient.DeleteAsync();
            }
        }
    }

    // ダウンロードしたファイル情報を返すクラス
    public class FileInfo
    {
        // ファイルデータのバイト配列
        public byte[] content { get; set; }
        public string contentType { get; set; }
    }
}
0
1
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
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?