In this Microsoft Azure article, we will create a storage container inside an Azure storage account using Azure SDK for .NET.
Estimated reading time: 3 minutes
Table of contents
Azure SDK for .NET allows us to use native C# code and create infrastructure resources on the Azure cloud platform.
Using .NET tools to manage Azure allows us to integrate Azure services with existing and new .NET applications.
The SDK also shorten the learning curve for developers looking to integrate and use .NET to build cloud-native applications or add services like storage, data and more to their applications.
Creating a Storage Container in Azure Using Azure SDK for .NET
This post will focus on creating a storage container inside an Azure storage account. We will start with the first infrastructure provision, which consists of a storage account using Azure PowerShell and Bicep.
Create Storage Account
We will use Azure PowerShell and the following commands to create a resource group and a storage account.
# Login to Azure (if not already logged in)
Connect-AzAccount
# Create a new resource group named 'bicep-lab' in a specific location (e.g., East US)
New-AzResourceGroup -Name "bicep-lab" -Location "EastUS"
Once the resource group is ready, we will create a storage account using Bicep. Azure Bicep is an Azure-only Infrastructure-as-code(IaC) tool that allows us to programmatically provision infrastructure and services on Azure.
Bicep is similar to Terraform but only works on Azure, uses the latest Azure API, and stores the state files in Azure.
The following Bicep file contains the deployment file for a storage account.
param storageAccountName string = 'deploycontainers1001'
param location string = 'eastus'
param skuName string = 'Standard_LRS'
resource storageAccount 'Microsoft.Storage/storageAccounts@2023-01-01' = {
name: storageAccountName
location: location
sku: {
name: skuName
}
kind: 'StorageV2'
properties: {
accessTier: 'Hot'
}
}
To create the storage account, run the following commands.
# Install Bicep on Windows
winget install -e --id Microsoft.Bicep
# Deploy storage account
New-AzResourceGroupDeployment -ResourceGroupName "bicep-lab" -TemplateFile .\main.bicep
Retrieve Storage Account Connection String Using PowerShell
Before we can access the storage account for our C# Console application, we need to retrieve the storage account’s connection string.
I will use the PowerShell script to retrieve the connection string from the storage account.
$rgname="bicep-lab"
$storageAccountName="deploycontainers1001"
$storageAccountKeys = Get-AzStorageAccountKey -ResourceGroupName $rgname -Name $storageAccountName
# Construct the connection string
$connectionString = "DefaultEndpointsProtocol=https;AccountName=$storageAccountName;AccountKey=$($storageAccountKeys[0].Value);EndpointSuffix=core.windows.net"
# Output the connection string
Write-Output $connectionString
Copy the connection string and save it for the next section.
Create C# Console Application
To create a storage container on Azure, we must first create a console application and install the Azure SDK storage libraries.
# Create C# Console application
dotnet new console
# Install the Azure Storage SDK library
dotnet add package Azure.Storage.Blobs
Create an Environment Variable
To connect to the storage account, the console app needs the connection string details to authenticate to Azure.
Using the connection string we copied from the previous section, create an environment variable called connectionString, as shown below.
$env:connectionString="connection string details"
Console App Code
Copy the following code to your Program.cs file and run the application. The application will create a container with a random name of deploycontainers and today’s date.
using Azure.Storage.Blobs; // Namespace for Blob storage types
using Azure.Storage.Blobs.Models; // Namespace for Blob storage models
class Program
{
static void Main(string[] args)
{
// Retrieve the connection string from environment variables
string connectionString = Environment.GetEnvironmentVariable("connectionString");
// Check if the connection string is not null or empty
if (!string.IsNullOrEmpty(connectionString))
{
// Print the connection string to the console for verification
Console.WriteLine($"connectionString: {connectionString}");
}
else
{
// Inform the user that the connection string environment variable is not set
Console.WriteLine("The environment variable 'connectionString' is not set.");
}
// Initiate asynchronous processing with the Azure Blob Storage
ProcessAsync(connectionString).GetAwaiter().GetResult();
// Prompt the user to press enter to exit the application
Console.WriteLine("Press enter to exit the sample application.");
Console.ReadLine();
}
/// <summary>
/// Asynchronously processes operations against Azure Blob Storage.
/// It creates a Blob Service Client using the provided connection string,
/// creates a new container with a unique name, and prompts the user to verify its creation in the Azure portal.
/// </summary>
/// <param name="connectionString">The Azure Blob Storage connection string.</param>
/// <returns>A task representing the asynchronous operation.</returns>
static async Task ProcessAsync(string connectionString)
{
// Create a BlobServiceClient instance for interacting with the Azure Blob Storage
BlobServiceClient blobServiceClient = new BlobServiceClient(connectionString);
// Generate a unique name for the new container
string containerName = "deploycontainers" + DateTime.Now.ToString("yyyyMMddHHmmss");
// Create the container and obtain a reference to it
BlobContainerClient containerClient = await blobServiceClient.CreateBlobContainerAsync(containerName);
// Inform the user that the container has been created and prompt for manual verification in the Azure portal
Console.WriteLine($"A new container named '{containerName}' has been created successfully.");
}
}