Download a blob with .NET

This article shows how to download a blob using the Azure Storage client library for .NET. You can download blob data to various destinations, including a local file path, stream, or text string. You can also open a blob stream and read from it.

Prerequisites

Set up your environment

If you don't have an existing project, this section shows you how to set up a project to work with the Azure Blob Storage client library for .NET. The steps include package installation, adding using directives, and creating an authorized client object. For details, see Get started with Azure Blob Storage and .NET.

Install packages

From your project directory, install packages for the Azure Blob Storage and Azure Identity client libraries using the dotnet add package command. The Azure.Identity package is needed for passwordless connections to Azure services.

dotnet add package Azure.Storage.Blobs
dotnet add package Azure.Identity

Add using directives

Add these using directives to the top of your code file:

using Azure.Identity;
using Azure.Storage.Blobs;
using Azure.Storage.Blobs.Models;
using Azure.Storage.Blobs.Specialized;

Some code examples in this article might require additional using directives.

Create a client object

To connect an app to Blob Storage, create an instance of BlobServiceClient. The following example shows how to create a client object using DefaultAzureCredential for authorization:

public BlobServiceClient GetBlobServiceClient(string accountName)
{
    BlobServiceClient client = new(
        new Uri($"https://{accountName}.blob.core.windows.net"),
        new DefaultAzureCredential());

    return client;
}

You can register a service client for dependency injection in a .NET app.

You can also create client objects for specific containers or blobs. To learn more about creating and managing client objects, see Create and manage client objects that interact with data resources.

Authorization

The authorization mechanism must have the necessary permissions to perform a download operation. For authorization with Microsoft Entra ID (recommended), you need Azure RBAC built-in role Storage Blob Data Reader or higher. To learn more, see the authorization guidance for Get Blob (REST API).

Download a blob

You can use any of the following methods to download a blob:

You can also open a stream to read from a blob. The stream only downloads the blob as the stream is read from. You can use either of the following methods:

Download to a file path

The following example downloads a blob to a local file path. If the specified directory doesn't exist, the code throws a DirectoryNotFoundException. If the file already exists at localFilePath, it's overwritten by default during subsequent downloads.

public static async Task DownloadBlobToFileAsync(
    BlobClient blobClient,
    string localFilePath)
{
    await blobClient.DownloadToAsync(localFilePath);
}

Download to a stream

The following example downloads a blob by creating a Stream object and then downloads to that stream. If the specified directory doesn't exist, the code throws a DirectoryNotFoundException.

public static async Task DownloadBlobToStreamAsync(
    BlobClient blobClient,
    string localFilePath)
{
    FileStream fileStream = File.OpenWrite(localFilePath);

    await blobClient.DownloadToAsync(fileStream);

    fileStream.Close();
}

Download to a string

The following example assumes that the blob is a text file, and downloads the blob to a string:

public static async Task DownloadBlobToStringAsync(BlobClient blobClient)
{
    BlobDownloadResult downloadResult = await blobClient.DownloadContentAsync();
    string blobContents = downloadResult.Content.ToString();
}

Download from a stream

The following example downloads a blob by reading from a stream:

public static async Task DownloadBlobFromStreamAsync(
    BlobClient blobClient,
    string localFilePath)
{
    using (var stream = await blobClient.OpenReadAsync())
    {
        FileStream fileStream = File.OpenWrite(localFilePath);
        await stream.CopyToAsync(fileStream);
    }
}

Download a block blob with configuration options

You can define client library configuration options when downloading a blob. These options can be tuned to improve performance and enhance reliability. The following code examples show how to use BlobDownloadToOptions to define configuration options when calling a download method. Note that the same options are available for BlobDownloadOptions.

Specify data transfer options on download

You can configure the values in StorageTransferOptions to improve performance for data transfer operations. The following code example shows how to set values for StorageTransferOptions and include the options as part of a BlobDownloadToOptions instance. The values provided in this sample aren't intended to be a recommendation. To properly tune these values, you need to consider the specific needs of your app.

public static async Task DownloadBlobWithTransferOptionsAsync(
    BlobClient blobClient,
    string localFilePath)
{
    FileStream fileStream = File.OpenWrite(localFilePath);

    var transferOptions = new StorageTransferOptions
    {
        // Set the maximum number of parallel transfer workers
        MaximumConcurrency = 2,

        // Set the initial transfer length to 8 MiB
        InitialTransferSize = 8 * 1024 * 1024,

        // Set the maximum length of a transfer to 4 MiB
        MaximumTransferSize = 4 * 1024 * 1024
    };

    BlobDownloadToOptions downloadOptions = new BlobDownloadToOptions()
    {
        TransferOptions = transferOptions
    };

    await blobClient.DownloadToAsync(fileStream, downloadOptions);

    fileStream.Close();
}

To learn more about tuning data transfer options, see Performance tuning for uploads and downloads.

Specify transfer validation options on download

You can specify transfer validation options to help ensure that data is downloaded properly and hasn't been tampered with during transit. Transfer validation options can be defined at the client level using BlobClientOptions, which applies validation options to all methods called from a BlobClient instance.

You can also override transfer validation options at the method level using BlobDownloadToOptions. The following code example shows how to create a BlobDownloadToOptions object and specify an algorithm for generating a checksum. The checksum is then used by the service to verify data integrity of the downloaded content.

public static async Task DownloadBlobWithChecksumAsync(
    BlobClient blobClient,
    string localFilePath)
{
    FileStream fileStream = File.OpenWrite(localFilePath);

    var validationOptions = new DownloadTransferValidationOptions
    {
        AutoValidateChecksum = true,
        ChecksumAlgorithm = StorageChecksumAlgorithm.Auto
    };

    BlobDownloadToOptions downloadOptions = new BlobDownloadToOptions()
    {
        TransferValidation = validationOptions
    };

    await blobClient.DownloadToAsync(fileStream, downloadOptions);

    fileStream.Close();
}

The following table shows the available options for the checksum algorithm, as defined by StorageChecksumAlgorithm:

Name Value Description
Auto 0 Recommended. Allows the library to choose an algorithm. Different library versions may choose different algorithms.
None 1 No selected algorithm. Don't calculate or request checksums.
MD5 2 Standard MD5 hash algorithm.
StorageCrc64 3 Azure Storage custom 64-bit CRC.

Resources

To learn more about how to download blobs using the Azure Blob Storage client library for .NET, see the following resources.

Code samples

REST API operations

The Azure SDK for .NET contains libraries that build on top of the Azure REST API, allowing you to interact with REST API operations through familiar .NET paradigms. The client library methods for downloading blobs use the following REST API operation:

Client library resources

See also

  • This article is part of the Blob Storage developer guide for .NET. To learn more, see the full list of developer guide articles at Build your .NET app.