この演習に必要な using ステートメントを含む次の例に合うように、Program.cs ファイル内の開始コードを置き換えます。
C#
using Azure.Storage.Blobs;
using Azure.Storage.Blobs.Models;
using System;
using System.IO;
// See https://aka.ms/new-console-template for more information
Console.WriteLine("Hello, World!");
次の例に合わせて Program.cs のコードを更新します。 開発時にローカルのワークステーション上でコードを実行する場合、Azure CLI や Visual Studio など、Azure に対する認証のためにログインしている優先ツールの開発者の資格情報が使われます。
C#
using Azure.Storage.Blobs;
using Azure.Storage.Blobs.Models;
using System;
using System.IO;
using Azure.Identity;
// TODO: Replace <storage-account-name> with your actual storage account namevar blobServiceClient = new BlobServiceClient(
new Uri("https://<storage-account-name>.blob.core.windows.net"),
new DefaultAzureCredential());
必ず、BlobServiceClient の URI のストレージ アカウント名を更新してください。 ストレージ アカウント名は、Azure portal の概要ページで確認できます。
注意
Azure にデプロイした場合は、この同じコードを使用して、Azure で実行されているアプリケーションから Azure Storage への要求を認可できます。 ただし、Azure 内のアプリ上でマネージド ID を有効にする必要があります。 次に、そのマネージド ID が接続できるようにストレージ アカウントを構成します。 この Azure サービス間の接続を構成する詳細な手順については、Azure ホステッド アプリからの認証に関するチュートリアルを参照してください。
// Retrieve the connection string for use with the application. string connectionString = Environment.GetEnvironmentVariable("AZURE_STORAGE_CONNECTION_STRING");
// Create a BlobServiceClient object var blobServiceClient = new BlobServiceClient(connectionString);
// TODO: Replace <storage-account-name> with your actual storage account namevar blobServiceClient = new BlobServiceClient(
new Uri("https://<storage-account-name>.blob.core.windows.net"),
new DefaultAzureCredential());
//Create a unique name for the containerstring containerName = "quickstartblobs" + Guid.NewGuid().ToString();
// Create the container and return a container client object
BlobContainerClient containerClient = await blobServiceClient.CreateBlobContainerAsync(containerName);
UploadAsync を使用してコンテナーに BLOB をアップロードします。 このコード例では、コンテナーにアップロードするローカルの data ディレクトリにテキスト ファイルを作成します。
Program.cs ファイルの末尾に次のコードを追加します。
C#
// Create a local file in the ./data/ directory for uploading and downloadingstring localPath = "data";
Directory.CreateDirectory(localPath);
string fileName = "quickstart" + Guid.NewGuid().ToString() + ".txt";
string localFilePath = Path.Combine(localPath, fileName);
// Write text to the fileawait File.WriteAllTextAsync(localFilePath, "Hello, World!");
// Get a reference to a blob
BlobClient blobClient = containerClient.GetBlobClient(fileName);
Console.WriteLine("Uploading to Blob storage as blob:\n\t {0}\n", blobClient.Uri);
// Upload data from the local file, overwrite the blob if it already existsawait blobClient.UploadAsync(localFilePath, true);
Console.WriteLine("Listing blobs...");
// List all blobs in the containerawaitforeach (BlobItem blobItem in containerClient.GetBlobsAsync())
{
Console.WriteLine("\t" + blobItem.Name);
}
// Download the blob to a local file// Append the string "DOWNLOADED" before the .txt extension // so you can compare the files in the data directorystring downloadFilePath = localFilePath.Replace(".txt", "DOWNLOADED.txt");
Console.WriteLine("\nDownloading blob to\n\t{0}\n", downloadFilePath);
// Download the blob's contents and save it to a fileawait blobClient.DownloadToAsync(downloadFilePath);
// Clean up
Console.Write("Press any key to begin clean up");
Console.ReadLine();
Console.WriteLine("Deleting blob container...");
await containerClient.DeleteAsync();
Console.WriteLine("Deleting the local source and downloaded files...");
File.Delete(localFilePath);
File.Delete(downloadFilePath);
Console.WriteLine("Done");
using Azure.Storage.Blobs;
using Azure.Storage.Blobs.Models;
using Azure.Identity;
// TODO: Replace <storage-account-name> with your actual storage account namevar blobServiceClient = new BlobServiceClient(
new Uri("https://<storage-account-name>.blob.core.windows.net"),
new DefaultAzureCredential());
//Create a unique name for the containerstring containerName = "quickstartblobs" + Guid.NewGuid().ToString();
// Create the container and return a container client object
BlobContainerClient containerClient = await blobServiceClient.CreateBlobContainerAsync(containerName);
// Create a local file in the ./data/ directory for uploading and downloadingstring localPath = "data";
Directory.CreateDirectory(localPath);
string fileName = "quickstart" + Guid.NewGuid().ToString() + ".txt";
string localFilePath = Path.Combine(localPath, fileName);
// Write text to the fileawait File.WriteAllTextAsync(localFilePath, "Hello, World!");
// Get a reference to a blob
BlobClient blobClient = containerClient.GetBlobClient(fileName);
Console.WriteLine("Uploading to Blob storage as blob:\n\t {0}\n", blobClient.Uri);
// Upload data from the local fileawait blobClient.UploadAsync(localFilePath, true);
Console.WriteLine("Listing blobs...");
// List all blobs in the containerawaitforeach (BlobItem blobItem in containerClient.GetBlobsAsync())
{
Console.WriteLine("\t" + blobItem.Name);
}
// Download the blob to a local file// Append the string "DOWNLOADED" before the .txt extension // so you can compare the files in the data directorystring downloadFilePath = localFilePath.Replace(".txt", "DOWNLOADED.txt");
Console.WriteLine("\nDownloading blob to\n\t{0}\n", downloadFilePath);
// Download the blob's contents and save it to a fileawait blobClient.DownloadToAsync(downloadFilePath);
// Clean up
Console.Write("Press any key to begin clean up");
Console.ReadLine();
Console.WriteLine("Deleting blob container...");
await containerClient.DeleteAsync();
Console.WriteLine("Deleting the local source and downloaded files...");
File.Delete(localFilePath);
File.Delete(downloadFilePath);
Console.WriteLine("Done");
C#
using Azure.Storage.Blobs;
using Azure.Storage.Blobs.Models;
// TODO: Replace <storage-account-name> with your actual storage account namevar blobServiceClient = new BlobServiceClient("<storage-account-connection-string>");
//Create a unique name for the containerstring containerName = "quickstartblobs" + Guid.NewGuid().ToString();
// Create the container and return a container client object
BlobContainerClient containerClient = await blobServiceClient.CreateBlobContainerAsync(containerName);
// Create a local file in the ./data/ directory for uploading and downloadingstring localPath = "data";
Directory.CreateDirectory(localPath);
string fileName = "quickstart" + Guid.NewGuid().ToString() + ".txt";
string localFilePath = Path.Combine(localPath, fileName);
// Write text to the fileawait File.WriteAllTextAsync(localFilePath, "Hello, World!");
// Get a reference to a blob
BlobClient blobClient = containerClient.GetBlobClient(fileName);
Console.WriteLine("Uploading to Blob storage as blob:\n\t {0}\n", blobClient.Uri);
// Upload data from the local fileawait blobClient.UploadAsync(localFilePath, true);
Console.WriteLine("Listing blobs...");
// List all blobs in the containerawaitforeach (BlobItem blobItem in containerClient.GetBlobsAsync())
{
Console.WriteLine("\t" + blobItem.Name);
}
// Download the blob to a local file// Append the string "DOWNLOADED" before the .txt extension // so you can compare the files in the data directorystring downloadFilePath = localFilePath.Replace(".txt", "DOWNLOADED.txt");
Console.WriteLine("\nDownloading blob to\n\t{0}\n", downloadFilePath);
// Download the blob's contents and save it to a fileawait blobClient.DownloadToAsync(downloadFilePath);
// Clean up
Console.Write("Press any key to begin clean up");
Console.ReadLine();
Console.WriteLine("Deleting blob container...");
await containerClient.DeleteAsync();
Console.WriteLine("Deleting the local source and downloaded files...");
File.Delete(localFilePath);
File.Delete(downloadFilePath);
Console.WriteLine("Done");
コードの実行
このアプリでは、ローカルの data フォルダーにテスト ファイルが作成され、BLOB ストレージにアップロードされます。 次に、コンテナー内の BLOB を一覧表示し、ファイルを新しい名前でダウンロードして、古いファイルと新しいファイルを比較できるようにします。
Visual Studio を使用している場合は、F5 キーを押してコードをビルドして実行し、コンソール アプリと対話します。 .NET CLI を使用している場合は、お使いのアプリケーションのディレクトリに移動し、アプリケーションをビルドして実行します。
コンソール
dotnet build
コンソール
dotnet run
アプリの出力は次の例のようになります (読みやすくするために GUID 値は省略されています)。
出力
Azure Blob Storage - .NET quickstart sample
Uploading to Blob storage as blob:
https://mystorageacct.blob.core.windows.net/quickstartblobsGUID/quickstartGUID.txt
Listing blobs...
quickstartGUID.txt
Downloading blob to
./data/quickstartGUIDDOWNLOADED.txt
Press any key to begin clean up
Deleting blob container...
Deleting the local source and downloaded files...
Done