Azure Storage Blobs: Sample Code

This page provides sample code snippets to demonstrate common operations with Azure Blob Storage. Choose your preferred language to see the relevant examples.

C# Samples

1. Install the SDK

You'll need the Azure.Storage.Blobs NuGet package. Install it using the .NET CLI:

dotnet add package Azure.Storage.Blobs

2. Connect to your Blob Storage Account

Use your connection string to create a BlobServiceClient.

using Azure.Storage.Blobs;

// Replace with your actual connection string
string connectionString = "YOUR_AZURE_STORAGE_CONNECTION_STRING";
BlobServiceClient blobServiceClient = new BlobServiceClient(connectionString);

3. Upload a Blob

Create a container (if it doesn't exist) and upload a file.

using Azure.Storage.Blobs;
using System.IO;

// Get a client for a specific container
string containerName = "mycontainer";
BlobContainerClient containerClient = blobServiceClient.GetBlobContainerClient(containerName);
await containerClient.CreateIfNotExistsAsync();

// Get a client for a specific blob
string blobName = "my-blob.txt";
BlobClient blobClient = containerClient.GetBlobClient(blobName);

// Create a local file to upload
string localFilePath = "path/to/local/file.txt";
using (FileStream uploadFileStream = File.OpenRead(localFilePath))
{
    await blobClient.UploadAsync(uploadFileStream, true);
}

Console.WriteLine($"Uploaded blob '{blobName}' to container '{containerName}'.");

4. Download a Blob

Download the content of a blob to a local file.

using Azure.Storage.Blobs;
using System.IO;

string containerName = "mycontainer";
string blobName = "my-blob.txt";
string downloadFilePath = "path/to/downloaded/file.txt";

BlobClient blobClient = blobServiceClient.GetBlobContainerClient(containerName).GetBlobClient(blobName);

using (var downloadFileStream = File.OpenWrite(downloadFilePath))
{
    Response download = await blobClient.DownloadAsync();
    await download.Value.Content.CopyToAsync(downloadFileStream);
}

Console.WriteLine($"Downloaded blob '{blobName}' to '{downloadFilePath}'.");

5. List Blobs in a Container

Iterate through all blobs in a specified container.

using Azure.Storage.Blobs;

string containerName = "mycontainer";
BlobContainerClient containerClient = blobServiceClient.GetBlobContainerClient(containerName);

Console.WriteLine("Blobs in container:");
await foreach (BlobItem blobItem in containerClient.GetBlobsAsync())
{
    Console.WriteLine($" - {blobItem.Name}");
}