Azure Storage データ移動ライブラリは、BLOB およびファイルをハイ パフォーマンスでアップロード、ダウンロード、およびコピーできるように設計された、クロスプラットフォームのオープンソース ライブラリです。 データ移動ライブラリには、.NET 用の Azure Storage クライアント ライブラリでは使用できない便利なメソッドが用意されています。 これらのメソッドを使用すると、並列操作数を設定したり、転送の進行状況を追跡したり、取り消された転送を再開したりすることができます。
データ移動ライブラリは .NET でのみ使用でき、Azure Blob Storage と Azure Files のみをサポートします。 You should consider these limitations and other known issues when deciding whether to use the Data Movement library.
If you're migrating code from the older Microsoft.Azure.Storage.DataMovement library (version 2.X.X) to the current Azure.Storage.DataMovement library (version 12.X.X), see the Migration guide.
API リファレンス ドキュメント | ソース コード | パッケージ (NuGet) | サンプル: Blobs / Files.Shares
Prerequisites
- Azure サブスクリプション - 無料アカウントを作成する
- Azure Storage アカウント - ストレージ アカウントの作成
- Latest .NET SDK for your operating system. ランタイムではなく、必ず SDK を入手してください。
環境を設定する
既存のプロジェクトがない場合、このセクションでは、.NET 用 Azure Blob Storage クライアント ライブラリを使用するようにプロジェクトを設定する方法について説明します。 このステップには、パッケージのインストール、using
ディレクティブの追加、承認されたクライアント オブジェクトの作成が含まれます。
Install packages
プロジェクト ディレクトリから、dotnet add package
コマンドを使用して、Azure Storage データ移動クライアント ライブラリと Azure Identity クライアント ライブラリのパッケージをインストールします。 The Azure.Identity package is needed for passwordless connections to Azure services.
dotnet add package Azure.Storage.DataMovement
dotnet add package Azure.Storage.DataMovement.Blobs
dotnet add package Azure.Identity
To work with extension library for Azure Files, install the Azure.Storage.DataMovement.Files.Shares package:
dotnet add package Azure.Storage.DataMovement.Files.Shares
using
ディレクティブを追加します
この記事のコード例を実行するには、次の using
ディレクティブを追加します。
using Azure;
using Azure.Core;
using Azure.Identity;
using Azure.Storage.DataMovement;
using Azure.Storage.DataMovement.Blobs;
Azure Files の拡張ライブラリを使用している場合は、次の using
ディレクティブを追加します。
using Azure.Storage.DataMovement.Files.Shares;
Authorization
認可メカニズムには、アップロード、ダウンロード、またはコピー操作を実行するために必要なアクセス許可が必要です。 Microsoft Entra ID を使用した認可 (推奨) には、Azure RBAC 組み込みロールのストレージ BLOB データ共同作成者以上が必要です。
データ移動ライブラリについて
Azure Storage データ移動ライブラリは、共通クライアント ライブラリと、Azure Blob Storage および Azure Files 用の拡張ライブラリで構成されています。 共通ライブラリはデータ転送のコア機能を提供し、拡張ライブラリは Blob Storage と Azure Files に固有の機能を提供します。 詳細については、次のリソースを参照してください。
TransferManager
オブジェクトを作成します
TransferManager is the main class for starting and controlling all types of transfers, including upload, download, and copy. このセクションでは、ローカル ファイル システム、Blob Storage、または Azure Files を操作するための TransferManager
オブジェクトを作成する方法について説明します。
Note
Azure SDK クライアント管理のベスト プラクティスは、クライアントをシングルトンとして扱うことです。つまり、クラスには一度に 1 つのオブジェクトだけを含めます。 コンストラクター パラメーターまたはクライアント オプションの特定のセットに対して、クライアントのインスタンスを複数保持する必要はありません。
次のコードは、TransferManager
オブジェクトを作成する方法を示しています。
TransferManager transferManager = new(new TransferManagerOptions());
You can optionally provide an instance of TransferManagerOptions to the constructor, which applies certain configuration options to all transfers started by the TransferManager
object. 次の構成オプションを使用できます。
- CheckpointStoreOptions: Optional. 転送を再開できるように、転送状態の保存に使用するチェックポイントを作成するためのオプションを定義します。
- Diagnostics: Gets the transfer manager diagnostic options.
- 転送中のエラーの処理方法を定義します。 既定値は
StopOnAnyFailure
です。 Default isStopOnAnyFailure
. - MaximumConcurrency: The maximum number of workers that can be used in a parallel transfer.
- ProvidersForResuming: Resource providers for the transfer manager to use in resuming a transfer. 使用中の記憶域プロバイダーごとに 1 つのプロバイダーが必要です。 詳細については、「既存の転送を再開する」を参照してください。
StorageResource
オブジェクトを作成します
StorageResource is the base class for all storage resources, including blobs and files.
StorageResource
オブジェクトを作成するには、次のいずれかのプロバイダー クラスを使用します。
-
BlobsStorageResourceProvider: Use this class to create
StorageResource
instances for a blob container, block blob, append blob, or page blob. -
ShareFilesStorageResourceProvider: Use this class to create
StorageResource
instances for a file or directory. -
LocalFilesStorageResourceProvider: Use this class to create
StorageResource
instances for a local file system.
Blob Storage 用の StorageResource
オブジェクトを作成する
次のコードは、StorageResource
を使用して BLOB コンテナーおよび BLOB 用の Uri
オブジェクトを作成する方法を示しています。
// Create a token credential
TokenCredential tokenCredential = new DefaultAzureCredential();
BlobsStorageResourceProvider blobsProvider = new(tokenCredential);
// Get a container resource
StorageResource container = await blobsProvider.FromContainerAsync(
new Uri("http://<storage-account-name>.blob.core.windows.net/sample-container"));
// Get a block blob resource - default is block blob
StorageResource blockBlob = await blobsProvider.FromBlobAsync(
new Uri("http://<storage-account-name>.blob.core.windows.net/sample-container/sample-block-blob"),
new BlockBlobStorageResourceOptions());
// Use a similar approach to get a page blob or append blob resource
You can also create a StorageResource
object using a client object from Azure.Storage.Blobs.
// Create a token credential
TokenCredential tokenCredential = new DefaultAzureCredential();
BlobContainerClient blobContainerClient = new(
new Uri("https://<storage-account-name>.blob.core.windows.net/sample-container"),
tokenCredential);
StorageResource containerResource = BlobsStorageResourceProvider.FromClient(blobContainerClient);
BlockBlobClient blockBlobClient = blobContainerClient.GetBlockBlobClient("sample-block-blob");
StorageResource blockBlobResource = BlobsStorageResourceProvider.FromClient(blockBlobClient);
// Use a similar approach to get a page blob or append blob resource
新しい転送を開始する
すべての転送では、ソースと宛先を指定する必要があります。 ソースと宛先は両方とも StorageResource
型であり、StorageResourceContainer
または StorageResourceItem
のいずれかになります。 特定の転送では、ソースと宛先が同じ種類である必要があります。 たとえば、ソースが BLOB コンテナーである場合、宛先も BLOB コンテナーである必要があります。
次のメソッドを呼び出すことで、新しい転送を開始できます。
This method returns a TransferOperation object that represents the transfer.
TransferOperation
オブジェクトを使用して、転送の進行状況を監視したり、転送 ID を取得したりできます。 転送 ID は、転送を再開したり一時停止したりするために必要な、転送の一意識別子です。
You can optionally provide an instance of TransferOptions to StartTransferAsync
or ResumeTransferAsync
, which applies certain configuration options to a specific transfer. 次の構成オプションを使用できます。
-
CreationMode: Configures the behavior when a transfer encounters a resource that already exists. 新しい転送を開始するときの既定値は
FailIfExists
です。 転送を再開する場合の既定値は異なる可能性があります。 転送の開始時に正常に列挙されたすべてのリソースについては、CreationMode
が既定で使用される初期値になります。 残りのリソースについては、通常の既定値が適用されます。 - InitialTransferSize: The size of the first range request in bytes. 単一転送サイズがこの制限より小さい場合は、単一の要求でアップロードまたはダウンロードされます。 Transfers larger than this limit continue being downloaded or uploaded in chunks of size MaximumTransferChunkSize. 既定値は 32 MiB です。 転送を再開する場合、既定値は転送が最初に開始されたときに指定された値になります。
- MaximumTransferChunkSize: The maximum size to use for each chunk when transferring data in chunks. 既定値は 4 MiB です。 転送を再開する場合、既定値は転送が最初に開始されたときに指定された値になります。
- ProgressHandlerOptions: Optional. ProgressHandler の動作を変更するためのオプション。
例: ローカル ディレクトリを BLOB コンテナーにアップロードする
次のコード例は、新しい転送を開始してローカル ディレクトリを BLOB コンテナーにアップロードする方法を示しています。
// Create a token credential
TokenCredential tokenCredential = new DefaultAzureCredential();
TransferManager transferManager = new(new TransferManagerOptions());
BlobsStorageResourceProvider blobsProvider = new(tokenCredential);
string localDirectoryPath = "C:/path/to/directory";
Uri blobContainerUri = new Uri("https://<storage-account-name>.blob.core.windows.net/sample-container");
TransferOperation transferOperation = await transferManager.StartTransferAsync(
sourceResource: LocalFilesStorageResourceProvider.FromDirectory(localDirectoryPath),
destinationResource: await blobsProvider.FromContainerAsync(blobContainerUri));
await transferOperation.WaitForCompletionAsync();
例: コンテナーまたは BLOB をコピーする
データ移動ライブラリを使用して、2 つの StorageResource
インスタンス間でコピーできます。 BLOB リソースの場合、転送には Put Blob From URL 操作が使用され、サーバー間のコピーが実行されます。
次のコード例は、新しい転送を開始して、ソース BLOB コンテナー内のすべての BLOB を宛先 BLOB コンテナーにコピーする方法を示しています。 出力先コンテナーは既に存在している必要があります。 In this example, we set CreationMode to OverwriteIfExists
to overwrite any destination blobs that already exist. アプリのニーズに応じて CreationMode
プロパティを調整できます。
Uri sourceContainerUri = new Uri("https://<storage-account-name>.blob.core.windows.net/source-container");
Uri destinationContainerUri = new Uri("https://<storage-account-name>.blob.core.windows.net/dest-container");
TransferOperation transferOperation = await transferManager.StartTransferAsync(
sourceResource: await blobsProvider.FromContainerAsync(
sourceContainerUri,
new BlobStorageResourceContainerOptions()
{
BlobPrefix = "source/directory/prefix"
}),
destinationResource: await blobsProvider.FromContainerAsync(
destinationContainerUri,
new BlobStorageResourceContainerOptions()
{
// All source blobs are copied as a single type of destination blob
// Defaults to block blob, if not specified
BlobType = BlobType.Block,
BlobPrefix = "destination/directory/prefix"
}),
transferOptions: new TransferOptions()
{
CreationMode = StorageResourceCreationMode.OverwriteIfExists,
}
);
await transferOperation.WaitForCompletionAsync();
次のコード例は、新しい転送を開始してソース BLOB を宛先 BLOB にコピーする方法を示しています。 In this example, we set CreationMode to OverwriteIfExists
to overwrite the destination blob if it already exists. アプリのニーズに応じて CreationMode
プロパティを調整できます。
Uri sourceBlobUri = new Uri(
"https://<storage-account-name>.blob.core.windows.net/source-container/source-blob");
Uri destinationBlobUri = new Uri(
"https://<storage-account-name>.blob.core.windows.net/dest-container/dest-blob");
TransferOperation transferOperation = await transferManager.StartTransferAsync(
sourceResource: await blobsProvider.FromBlobAsync(sourceBlobUri),
destinationResource: await blobsProvider.FromBlobAsync(destinationBlobUri, new BlockBlobStorageResourceOptions()),
transferOptions: new TransferOptions()
{
CreationMode = StorageResourceCreationMode.OverwriteIfExists,
}
);
await transferOperation.WaitForCompletionAsync();
既存の転送を再開する
データ移動ライブラリでは、転送の進行状況をディスクに保持することで、完了前に失敗した転送や、取り消しまたは一時停止された転送を再開できます。 転送を再開するには、持続的なデータから転送を再構築できる TransferManager
インスタンスを使用して StorageResourceProvider
オブジェクトを構成する必要があります。 You can use the ProvidersForResuming
property of the TransferManagerOptions class to specify the providers.
次のコード例は、ローカル ファイル システムと Blob Storage 間の転送を再開できる TransferManager
オブジェクトを初期化する方法を示しています。
// Create a token credential
TokenCredential tokenCredential = new DefaultAzureCredential();
TransferManager transferManager = new(new TransferManagerOptions()
{
ProvidersForResuming = new List<StorageResourceProvider>()
{
new BlobsStorageResourceProvider(tokenCredential)
}
});
転送を再開するには、次のメソッドを呼び出します。
再開する転送の転送 ID を指定します。 転送 ID は、転送が開始されたときに TransferOperation
オブジェクトの一部として返される転送の一意識別子です。 If you don't know the transfer ID value, you can call TransferManager.GetTransfersAsync to find the transfer and its corresponding ID.
次のコード例は、転送を再開する方法を示しています。
TransferOperation resumedTransfer = await transferManager.ResumeTransferAsync(transferId: ID);
Note
The ___location of the persisted transfer data is different than the default ___location if TransferCheckpointStoreOptions is set as part of TransferManagerOptions
. カスタム チェックポイント ストアで記録された転送を再開するには、転送を再開する TransferManager
オブジェクトに同じチェックポイント ストア オプションを指定する必要があります。
転送の進行状況を監視する
転送は、アプリのニーズに応じて、いくつかのメカニズムを通じて監視および観察できます。 このセクションでは、TransferOperation
オブジェクトを使用して転送の進行状況を監視する方法と、TransferOptions
イベントを使用して転送を監視する方法について説明します。
例: TransferOperation
オブジェクトを使用して転送の進行状況を監視する
転送の進行状況は、TransferOperation
メソッドによって返される StartTransferAsync
オブジェクトを使用して監視できます。 You can also call TransferManager.GetTransfersAsync to enumerate all transfers for a TransferManager
object.
次のコード例は、すべての転送を反復処理し、各転送の状態をログ ファイルに書き込む方法を示しています。
async Task CheckTransfersAsync(TransferManager transferManager)
{
await foreach (TransferOperation transfer in transferManager.GetTransfersAsync())
{
using StreamWriter logStream = File.AppendText("path/to/log/file");
logStream.WriteLine(Enum.GetName(typeof(TransferState), transfer.Status.State));
}
}
TransferStatus defines the status of the transfer job.
TransferStatus
には、次のプロパティがあります。
Property | タイプ | Description |
---|---|---|
HasCompletedSuccessfully |
ブール値 | 転送に失敗した、またはスキップされた項目なしで正常に完了したかどうかを表します。 |
HasFailedItems |
ブール値 | 転送に失敗した項目があるかどうかを表します。
true に設定されている場合、転送には少なくとも 1 つの失敗した項目があります。
false に設定されている場合、転送には現状失敗はありません。 |
HasSkippedItems |
ブール値 | 転送にスキップされた項目があるかどうかを表します。
true に設定されている場合、転送には少なくとも 1 つのスキップされた項目があります。
false に設定されている場合、転送には現状スキップされた項目はありません。 It's possible to never have any items skipped if SkipIfExists isn't enabled in TransferOptions.CreationMode. |
State |
TransferState | 転送が持つことができる状態の種類を定義します。 See TransferState for details. |
例: TransferOptions
イベントを使用して転送の進行状況を監視する
You can monitor transfer progress by listening for events provided by the TransferOptions class. The TransferOptions
instance is passed to the StartTransferAsync
method and provides events that are triggered when a transfer completes, fails, is skipped, or changes status.
次のコード例は、TransferOptions
を使用して転送完了イベントをリッスンする方法を示しています。
async Task<TransferOperation> ListenToTransfersAsync(
TransferManager transferManager,
StorageResource source,
StorageResource destination)
{
TransferOptions transferOptions = new();
transferOptions.ItemTransferCompleted += (TransferItemCompletedEventArgs args) =>
{
using (StreamWriter logStream = File.AppendText("path/to/log/file"))
{
logStream.WriteLine($"File Completed Transfer: {args.Source.Uri.AbsoluteUri}");
}
return Task.CompletedTask;
};
return await transferManager.StartTransferAsync(
source,
destination,
transferOptions);
}
BlobContainerClient
の拡張メソッドを使用する
For applications with existing code that uses the BlobContainerClient
class from Azure.Storage.Blobs, you can use extension methods to start transfers directly from a BlobContainerClient
object. The extension methods are provided in the BlobContainerClientExtensions class (or ShareDirectoryClientExtensions for Azure Files), and provide some of the benefits of using TransferManager
with minimal code changes. このセクションでは、拡張メソッドを使用して BlobContainerClient
オブジェクトから転送を実行する方法について説明します。
Install the Azure.Storage.Blobs package if you don't have it already:
dotnet add package Azure.Storage.Blobs
コード ファイルの先頭に次の using
ディレクティブを追加します。
using Azure.Storage.Blobs;
using Azure.Storage.Blobs.Models;
次のコード例は、BlobContainerClient
という名前の BLOB コンテナー用の sample-container
をインスタンス化する方法を示しています。
// Create a token credential
TokenCredential tokenCredential = new DefaultAzureCredential();
BlobServiceClient client = new BlobServiceClient(
new Uri("https://<storage-account-name>.blob.core.windows.net"),
tokenCredential);
BlobContainerClient containerClient = client.GetBlobContainerClient("sample-container");
次のコード例は、sample-container
を使用してローカル ディレクトリの内容を UploadDirectoryAsync
にアップロードする方法を示しています。
TransferOperation transfer = await containerClient
.UploadDirectoryAsync(WaitUntil.Started, "local/directory/path");
await transfer.WaitForCompletionAsync();
次のコード例は、sample-container
を使用して DownloadToDirectoryAsync
の内容をローカル ディレクトリにダウンロードする方法を示しています。
TransferOperation transfer = await containerClient
.DownloadToDirectoryAsync(WaitUntil.Started, "local/directory/path");
await transfer.WaitForCompletionAsync();
BlobContainerClient
の拡張メソッドの詳細については、「BlobContainerClient の拡張機能」を参照してください。
Next step
- Code samples for DataMovement.Blobs and DataMovement.Files.Shares are available in the Azure SDK for .NET GitHub repository.