C#  

Using C# with Azure Blob Storage: Practical Examples with the Azure SDK for .NET

Introduction

Azure Blob Storage is Microsoft's object storage solution for the cloud. It's optimized for storing massive amounts of unstructured data. In this article, we'll explore how to use C# with Azure Blob Storage using the Azure SDK for .NET.

You will learn,

  • How to install and configure the Azure SDK
  • Uploading blobs to a container
  • Downloading blobs
  • Listing blobs
  • Deleting blobs
  • Using SAS Tokens for secure access

Let's dive in!

Setting Up Your Project

First, create a new C# console project or use an existing project.

Install Azure SDK for .NET

Use NuGet Package Manager Console.

Install-Package Azure.Storage.Blobs

This package provides APIs necessary to work with Azure Blob Storage.

Configuration

You need a connection string to access your Azure Storage Account.

You can find it in the Azure portal under Storage Account > Access Keys.

Example: Initialize BlobServiceClient

string connectionString = "your-azure-storage-connection-string";
var blobServiceClient = new BlobServiceClient(connectionString);

Note. For production, consider using Azure Managed Identity or Azure Key Vault for securing connection strings.

Uploading a Blob

Example. Code using BlobContainerClient

public static async Task UploadBlobAsync(string containerName, string blobName, string filePath)
{
    var blobServiceClient = new BlobServiceClient("your-connection-string");
    var containerClient = blobServiceClient.GetBlobContainerClient(containerName);
    await containerClient.CreateIfNotExistsAsync();

    BlobClient blobClient = containerClient.GetBlobClient(blobName);
    await blobClient.UploadAsync(filePath, overwrite: true);

    Console.WriteLine("Upload completed");
}

Explanation

  • Create or connect to a container.
  • Create a blob client from the container.
  • Upload the file asynchronously.

Call it like this.

await UploadBlobAsync("my-container", "folder/example.txt", "C:\\temp\\example.txt");

Downloading a Blob

Example Code

public static async Task DownloadBlobAsync(string containerName, string blobName, string downloadPath)
{
    var blobServiceClient = new BlobServiceClient("your-connection-string");
    var containerClient = blobServiceClient.GetBlobContainerClient(containerName);

    BlobClient blobClient = containerClient.GetBlobClient(blobName);
    await blobClient.DownloadToAsync(downloadPath);

    Console.WriteLine("Download completed");
}

Explanation

  • Connect to the container.
  • Create a BlobClient for the blob.
  • Download the blob to a local path.

Call it like this.

await DownloadBlobAsync("my-container", "folder/example.txt", "C:\\temp\\downloaded.txt");

Listing Blobs in a Container

Example Code

public static async Task ListBlobsAsync(string containerName)
{
    var blobServiceClient = new BlobServiceClient("your-connection-string");
    var containerClient = blobServiceClient.GetBlobContainerClient(containerName);

    await foreach (var blobItem in containerClient.GetBlobsAsync())
    {
        Console.WriteLine(blobItem.Name);
    }
}

Explanation

  • Retrieves all blobs in the specified container.
  • Uses asynchronous iteration for efficiency.

Call it like this.

await ListBlobsAsync("my-container");

Deleting a Blob

Example Code

public static async Task DeleteBlobAsync(string containerName, string blobName)
{
    var blobServiceClient = new BlobServiceClient("your-connection-string");
    var containerClient = blobServiceClient.GetBlobContainerClient(containerName);

    BlobClient blobClient = containerClient.GetBlobClient(blobName);
    await blobClient.DeleteIfExistsAsync();

    Console.WriteLine("Blob deleted successfully");
}

Explanation

  • Attempts to delete the blob if it exists.
  • Avoids exceptions if the blob doesn't exist.

Call it like this.

await DeleteBlobAsync("my-container", "folder/example.txt");

Generating SAS Tokens for Secure Access

Example Code

public static string GenerateSasToken(string containerName, string blobName, BlobSasPermissions permissions, DateTimeOffset expiresOn)
{
    var blobServiceClient = new BlobServiceClient("your-connection-string");
    var containerClient = blobServiceClient.GetBlobContainerClient(containerName);
    var blobClient = containerClient.GetBlobClient(blobName);

    if (blobClient.CanGenerateSasUri)
    {
        var sasBuilder = new BlobSasBuilder(permissions, expiresOn)
        {
            BlobContainerName = containerName,
            BlobName = blobName
        };

        Uri sasUri = blobClient.GenerateSasUri(sasBuilder);
        return sasUri.ToString();
    }
    else
    {
        throw new InvalidOperationException("SAS generation not permitted.");
    }
}

Explanation

  • SAS tokens allow time-limited, permission-controlled access to blobs without exposing account keys.
  • Great for sharing temporary access securely.

Call it like this.

var sasUrl = GenerateSasToken("my-container", "folder/example.txt", BlobSasPermissions.Read, DateTimeOffset.UtcNow.AddHours(1));
Console.WriteLine(sasUrl);

Best Practices

  • Secure connection strings: Use environment variables, Azure Identity libraries, or Managed Identity.
  • Error handling: Always wrap Azure SDK calls in try-catch blocks.
  • Container naming: Stick to lowercase letters, numbers, and hyphens.
  • Asynchronous programming: Use async/await for all storage operations to maximize performance.
  • Logging: Monitor storage activities using Azure Monitor and Application Insights.

Conclusion

Using Azure Blob Storage with C# is simple and powerful with the Azure SDK for .NET. In this article, you learned how to upload, download, list, delete blobs, and generate SAS tokens for secure access.

With these skills, you can build applications that scale effortlessly, securely store large amounts of unstructured data, and share files across services.