Azure Blob Storage .NET SDK Reference
This document provides a comprehensive reference for using the Azure Blob Storage .NET SDK to interact with your blob data. You'll find information on key classes, methods, and best practices.
Getting Started
To use the Azure Blob Storage .NET SDK, you first need to install the relevant NuGet package:
dotnet add package Azure.Storage.Blobs
Next, you'll need to instantiate a BlobServiceClient using your storage account connection string or shared access signature (SAS) token. It's recommended to store your connection strings securely, for example, in Azure Key Vault or application configuration settings.
using Azure.Storage.Blobs;
// Replace with your actual connection string
string connectionString = "YOUR_AZURE_STORAGE_CONNECTION_STRING";
BlobServiceClient blobServiceClient = new BlobServiceClient(connectionString);
Key Classes
BlobServiceClient: The primary client for interacting with the Azure Blob Storage service.BlobContainerClient: Represents a blob container. Used for managing containers and their blobs.BlobClient: Represents a single blob. Used for operations on individual blobs like uploading, downloading, and deleting.BlobProperties: Contains metadata about a blob.ListBlobsResult: The result of a blob listing operation.
Common Operations
Creating a Container
Use the CreateBlobContainerAsync method on BlobServiceClient to create a new container.
await blobServiceClient.CreateBlobContainerAsync("my-new-container");
Console.WriteLine("Container 'my-new-container' created successfully.");
Uploading a Blob
You can upload blobs from a local file or a memory stream. This example shows uploading from a file.
// Get a client for the container
BlobContainerClient containerClient = blobServiceClient.GetBlobContainerClient("my-container");
// Get a client for the blob
string blobName = "my-local-file.txt";
BlobClient blobClient = containerClient.GetBlobClient(blobName);
// Upload the blob from a local file
using (FileStream uploadFileStream = File.OpenRead("path/to/my-local-file.txt"))
{
await blobClient.UploadAsync(uploadFileStream, true); // true to overwrite if blob exists
Console.WriteLine($"Blob '{blobName}' uploaded successfully.");
}
Downloading a Blob
Download a blob to a local file or a memory stream.
string blobName = "my-local-file.txt";
BlobClient blobClient = containerClient.GetBlobClient(blobName);
// Download the blob to a local file
string downloadFilePath = "path/to/downloaded-file.txt";
await blobClient.DownloadToAsync(downloadFilePath);
Console.WriteLine($"Blob '{blobName}' downloaded to '{downloadFilePath}'.");
// Alternatively, download to a memory stream
// using (MemoryStream downloadStream = new MemoryStream())
// {
// await blobClient.DownloadToAsync(downloadStream);
// // Process the stream
// }
Listing Blobs in a Container
Iterate through blobs within a container.
Console.WriteLine("Listing blobs:");
await foreach (BlobItem blobItem in containerClient.GetBlobsAsync())
{
Console.WriteLine($" - {blobItem.Name}");
}
Error Handling
The SDK throws exceptions for failed operations. It's crucial to wrap your SDK calls in try-catch blocks to handle potential issues like network errors, authentication failures, or resource not found exceptions.
try
{
// Your blob operation here
await blobClient.DeleteAsync();
Console.WriteLine("Blob deleted.");
}
catch (RequestFailedException ex)
{
Console.WriteLine($"Error deleting blob: {ex.Message}");
// Handle specific status codes if needed
if (ex.Status == 404)
{
Console.WriteLine("Blob not found.");
}
}
catch (Exception ex)
{
Console.WriteLine($"An unexpected error occurred: {ex.Message}");
}
Advanced Features
- Blob Leases: For concurrency control.
- Blob Snapshots: Create read-only versions of blobs.
- Access Tiers: Manage cost by setting access tiers (Hot, Cool, Archive).
- Blob Index Tags: Tag blobs for organization and retrieval.
For more in-depth information on these features, please refer to the official Azure Blob Storage documentation.
Note
Always use asynchronous methods (e.g., UploadAsync, DownloadToAsync) for I/O-bound operations to keep your application responsive.