Create and manage a blob snapshot in .NET
A snapshot is a read-only version of a blob that's taken at a point in time. This article shows how to create and manage blob snapshots using the Azure Storage client library for .NET.
For more information about blob snapshots in Azure Storage, see Blob snapshots.
Create a snapshot
To create a snapshot of a block blob using version 12.x of the Azure Storage client library for .NET, use one of the following methods:
The following code example shows how to create a snapshot with version 12.x. Include a reference to the Azure.Identity library to use your Azure AD credentials to authorize requests to the service. For more information about using the DefaultAzureCredential class to authorize a managed identity to access Azure Storage, see Azure Identity client library for .NET.
private static async Task CreateBlockBlobSnapshot(string accountName, string containerName, string blobName, Stream data)
{
const string blobServiceEndpointSuffix = ".blob.core.windows.net";
Uri containerUri = new Uri("https://" + accountName + blobServiceEndpointSuffix + "/" + containerName);
// Get a container client object and create the container.
BlobContainerClient containerClient = new BlobContainerClient(containerUri,
new DefaultAzureCredential());
await containerClient.CreateIfNotExistsAsync();
// Get a blob client object.
BlobClient blobClient = containerClient.GetBlobClient(blobName);
try
{
// Upload text to create a block blob.
await blobClient.UploadAsync(data);
// Add blob metadata.
IDictionary<string, string> metadata = new Dictionary<string, string>
{
{ "ApproxBlobCreatedDate", DateTime.UtcNow.ToString() },
{ "FileType", "text" }
};
await blobClient.SetMetadataAsync(metadata);
// Sleep 5 seconds.
System.Threading.Thread.Sleep(5000);
// Create a snapshot of the base blob.
// You can specify metadata at the time that the snapshot is created.
// If no metadata is specified, then the blob's metadata is copied to the snapshot.
await blobClient.CreateSnapshotAsync();
}
catch (RequestFailedException e)
{
Console.WriteLine(e.Message);
Console.ReadLine();
throw;
}
}
Delete snapshots
To delete a blob, you must first delete any snapshots of that blob. You can delete a snapshot individually, or specify that all snapshots be deleted when the source blob is deleted. If you attempt to delete a blob that still has snapshots, an error results.
To delete a blob and its snapshots using version 12.x of the Azure Storage client library for .NET, use one of the following methods, and include the DeleteSnapshotsOption enum:
The following code example shows how to delete a blob and its snapshots in .NET, where blobClient
is an object of type BlobClient):
await blobClient.DeleteIfExistsAsync(DeleteSnapshotsOption.IncludeSnapshots, null, default);
Next steps
Feedback
Submit and view feedback for