0
0

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.

Azure Blob Storage から Blob のダウンロード方法として、Azure CLI より .NET 用の SDK を使った方が断然早い

Last updated at Posted at 2023-08-03

背景

Azure Blob Storage から Blob をダウンロードする方法はいくつかあるが、Azure CLI を使った方法は非常に時間がかかる。AZコマンドを実行しても動作するまでの無の時間も長い。

今回は Microsoft が提供している .NET 用の SDK を使った方法がとても速かったので、2つのパターンでコードを紹介する。Azure CLI と比べてざっと 15 倍違った。

環境は .NET 6 を使用する。

初期化

ダウンロード先はダウンロードフォルダ

using Azure.Storage.Blobs;
using Azure.Storage.Blobs.Models;

string connectionString = "<あなたの情報を入力してください>";
string containerName = "<あなたの情報を入力してください>";

BlobServiceClient blobServiceClient = new(connectionString);
BlobContainerClient containerClient = blobServiceClient.GetBlobContainerClient(containerName);

string receivePath = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile) + @$"\Downloads\{containerName}\";

【パターン1】Blob コンテナにある Blob の Prefix を指定してダウンロードする方法

foreach (BlobHierarchyItem blobHierarchyItem in containerClient.GetBlobsByHierarchy(prefix: "<指定したい Prefix>"))
{
    // 特定の文字列が含まれている Blob のみをダウンロードしたい場合
    //if (!blobHierarchyItem.Blob.Name.Contains("<特定の文字列>"))
    //{
    //    continue;
    //}

    string blobFilePath = receivePath + blobHierarchyItem.Blob.Name;
    string? blobDirectoryPath = Path.GetDirectoryName(blobFilePath);
    if (blobDirectoryPath is null)
    {
        return;
    }

    if (!Directory.Exists(blobDirectoryPath))
    {
        Directory.CreateDirectory(blobDirectoryPath);
    }

    BlobClient blobClient = containerClient.GetBlobClient(blobHierarchyItem.Blob.Name);

    using FileStream fileStream = File.OpenWrite(blobFilePath);
    await blobClient.DownloadToAsync(fileStream);
    Console.WriteLine(blobHierarchyItem.Blob.Name);
}

【パターン2】Blob コンテナを全探索してダウンロードする方法

foreach (BlobItem blobItem in containerClient.GetBlobs())
{
    // 特定の文字列が含まれている Blob のみをダウンロードしたい場合
    //if (!blobItem.Name.Contains("<特定の文字列>"))
    //{
    //    continue;
    //}

    string blobFilePath = receivePath + blobItem.Name;
    string? blobDirectoryPath = Path.GetDirectoryName(blobFilePath);
    if (blobDirectoryPath is null)
    {
        return;
    }

    if (!Directory.Exists(blobDirectoryPath))
    {
        Directory.CreateDirectory(blobDirectoryPath);
    }

    BlobClient blobClient = containerClient.GetBlobClient(blobItem.Name);

    using FileStream fileStream = File.OpenWrite(blobFilePath);
    await blobClient.DownloadToAsync(fileStream);
    Console.WriteLine(blobItem.Name);
}
0
0
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
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?