Azure Blob Storage using a .NET Core Console Application
Getting start with the Azure Blob Storage Client Library v12 for .NET.
Azure Blob Storage is Microsoft’s object storage solution for the cloud. This solution is optimized for storing massive amounts of unstructed data (pictures, files or docs for example).
You can create containers, upload blobs to azure storage, list all of the blobs in a container, download the blobs to your local computer or delete containers easily using the Azure Blob Storage Client Library v12!
Prerequisites
Azure subscription - create one for free!
Azure storage account - create a storage account here
The current .NET Core SDK for your OS. (not the runtime) (currently I’m running .NET Core 3.0)
Let’s go!
First you need create the .NET Core project. I’ll use BlobStorageV12 name. In a terminal (such as cmder, PowerShell or VS Code Terminal) type:
dotnet new console -n BlobStorageV12
Then switch to the new directory
cd .\BlobStorageV12\
Still in the BlobStorageV12 directory install the Azure Blob Storage Client Library for .NET package typing:
dotnet add package Azure.Storage.Blobs
Now let’s set up the app framework!
Open the Program.cs file and update like that:
using Azure.Storage;
using Azure.Storage.Blobs;
using Azure.Storage.Blobs.Models;
using System;
using System.IO;
using System.Threading.Tasks;namespace BlobStorageV12
{
class Program
{
static void Main(string[] args)
{
}
}
}
Copy your credentials from the Azure Portal (Storage Accounts >> Settings >> Access Keys >> Connection String (under key1)) and create an environment variable in a terminal typing (windows):
setx CONNECT_STR="[yourconnectionstringhere]"
note: you will need restart any running programs that will need to read the environment variable. Restart VSCode or other editor before continuing.
Probably you know it but look the diagram showing the relationship between the storage account, a container in the storage account and a blob in a container:
Use the following .NET classes to interact with these resources:
- BlobServiceClient: The
BlobServiceClient
class allows you to manipulate Azure Storage resources and blob containers. - BlobContainerClient: The
BlobContainerClient
class allows you to manipulate Azure Storage containers and their blobs. - BlobClient: The
BlobClient
class allows you to manipulate Azure Storage blobs. - BlobDownloadInfo: The
BlobDownloadInfo
class represents the properties and content returned from downloading a blob.
Ok, ok but let’s code!
Inside the Main method type:
Console.WriteLine("Azure Blob Storage V12 - .NET sample");string connectionString = Environment.GetEnvironmentVariable("CONNECT_STR");Console.WriteLine(connectionString); //here you can see if the environment variable is workingConsole.ReadKey();// dotnet run to check it
Create a Container
You can choise the Container name. First create a new instance of BlobServiceClient. Then call the CreateBlobContainerAsync method to create the container in your storage account. We will append a GUID value to the container name to ensure that it’s unique. Still the Main method update the Code:
Console.WriteLine("Azure Blob Storage V12 - .NET sample");string connectionString = Environment.GetEnvironmentVariable("CONNECT_STR");BlobServiceClient blobServiceClient = new BlobServiceClient(connectionString);string containerName = "blobfromapp" + Guid.NewGuid().ToString();BlobContainerClient containerClient = await blobServiceClient.CreateBlobContainerAsync(containerName);// dotnet run to check it
note: now the Main method is a task and we are using a blob async creation
Upload blobs to a container
Create a directory named data (sample). We’ll use this directory for uploading and downloading.
Add this code to the end of the Main method:
string localPath = "../data/";string fileName = "myFile" + Guid.NewGuid().ToString() + ".txt";string localFilePath = Path.Combine(localPath, fileName);await File.WriteAllTextAsync(localFilePath, "Hello, Mediums");BlobClient blobClient = containerClient.GetBlobClient(fileName);Console.WriteLine($"Uploading to Blob Storage:\n\t {blobClient.Uri}\n");using FileStream uploadFileStream = File.OpenRead(localFilePath);await blobClient.UploadAsync(uploadFileStream);uploadFileStream.Close();// dotnet run to check it
Check the Azure Storage Explorer
Listing the Blobs in a Container
Still in Main method (c’mon it’s just a sample) add this code to the end:
await foreach (BlobItem item in containerClient.GetBlobsAsync()) Console.WriteLine(item.Name);
Downloading blobs
Let’s call the DownloadAsync to do it! Add this code to de end of the Main method:
string downloadFilePath = localFilePath.Replace(".txt", "Download.txt");
Console.WriteLine($"Downloading blob to\n\t{ downloadFilePath }\n");
BlobDownloadInfo download = await blobClient.DownloadAsync();using FileStream downloadFileStream = File.OpenWrite(downloadFilePath);await download.Content.CopyToAsync(downloadFileStream);
downloadFileStream.Close();
Deleting a Container
Using DeleteAsync let’s delete a container. Adding this code to the end of the Main method we can delete a container easily! Look:
Console.WriteLine("Type y to Delete or n to exit:\n");bool choise = Console.ReadLine() == "y" ? true : false;if (choise){
await containerClient.DeleteAsync();
File.Delete(localFilePath);
File.Delete(downloadFilePath);
Console.WriteLine("Done!");
} else
Console.WriteLine("Exiting..");
In this document you learned how to manage blobs using .NET Core. I hope it was helpful.
You can get the full code in my GitHub.
See you.
credits: https://docs.microsoft.com/en-us/azure/storage/blobs/storage-quickstart-blobs-dotnet