Quickstart: Azure Blob storage client library for .NET

Get started with the Azure Blob Storage client library for .NET. Azure Blob Storage is Microsoft's object storage solution for the cloud. Follow steps to install the package and try out example code for basic tasks. Blob storage is optimized for storing massive amounts of unstructured data.

Use the Azure Blob Storage client library for .NET to:

  • Create a container
  • Set permissions on a container
  • Create a blob in Azure Storage
  • Download the blob to your local computer
  • List all of the blobs in a container
  • Delete a container

API reference documentation | Library source code | Package (NuGet) | Samples

Prerequisites

Setting up

This section walks you through preparing a project to work with the Azure Blob Storage client library for .NET.

Create the project

First, create a .NET Core application named blob-quickstart.

  1. In a console window (such as cmd, PowerShell, or Bash), use the dotnet new command to create a new console app with the name blob-quickstart. This command creates a simple "Hello World" C# project with a single source file: Program.cs.

    dotnet new console -n blob-quickstart
    
  2. Switch to the newly created blob-quickstart folder and build the app to verify that all is well.

    cd blob-quickstart
    
    dotnet build
    

The expected output from the build should look something like this:

C:\QuickStarts\blob-quickstart> dotnet build
Microsoft (R) Build Engine version 16.0.450+ga8dc7f1d34 for .NET Core
Copyright (C) Microsoft Corporation. All rights reserved.

  Restore completed in 44.31 ms for C:\QuickStarts\blob-quickstart\blob-quickstart.csproj.
  blob-quickstart -> C:\QuickStarts\blob-quickstart\bin\Debug\netcoreapp2.1\blob-quickstart.dll

Build succeeded.
    0 Warning(s)
    0 Error(s)

Time Elapsed 00:00:03.08

Install the package

While still in the application directory, install the Azure Blob Storage client library for .NET package by using the dotnet add package command.

dotnet add package Microsoft.Azure.Storage.Blob

Set up the app framework

From the project directory:

  1. Open the Program.cs file in your editor
  2. Remove the Console.WriteLine statement
  3. Add using directives
  4. Create a ProcessAsync method where the main code for the example will reside
  5. Asynchronously call the ProcessAsync method from Main

Here's the code:

using System;
using System.IO;
using System.Threading.Tasks;
using Microsoft.Azure.Storage;
using Microsoft.Azure.Storage.Blob;

namespace blob_quickstart
{
    class Program
    {
        public static void Main()
        {
            Console.WriteLine("Azure Blob Storage - .NET quickstart sample\n");

            // Run the examples asynchronously, wait for the results before proceeding
            ProcessAsync().GetAwaiter().GetResult();

            Console.WriteLine("Press any key to exit the sample application.");
            Console.ReadLine();
        }

        private static async Task ProcessAsync()
        {
        }
    }
}

Copy your credentials from the Azure portal

The sample application needs to authenticate access to your storage account. To authenticate, add your storage account credentials to the application as a connection string. View your storage account credentials by following these steps:

  1. Navigate to the Azure portal.

  2. Locate your storage account.

  3. In the Settings section of the storage account overview, select Access keys. Here, you can view your account access keys and the complete connection string for each key.

  4. Find the Connection string value under key1, and select the Copy button to copy the connection string. You will add the connection string value to an environment variable in the next step.

    Screenshot showing how to copy a connection string from the Azure portal

Configure your storage connection string

After you have copied your connection string, write it to a new environment variable on the local machine running the application. To set the environment variable, open a console window, and follow the instructions for your operating system. Replace <yourconnectionstring> with your actual connection string.

After you add the environment variable, you may need to restart any running programs that will need to read the environment variable. For example, if you are using Visual Studio as your editor, restart Visual Studio before running the example.

Windows

setx STORAGE_CONNECTION_STRING "<yourconnectionstring>"

Linux

export STORAGE_CONNECTION_STRING="<yourconnectionstring>"

MacOS

export STORAGE_CONNECTION_STRING="<yourconnectionstring>"

Object model

Azure Blob storage is optimized for storing massive amounts of unstructured data. Unstructured data is data that does not adhere to a particular data model or definition, such as text or binary data. Blob storage offers three types of resources:

  • The storage account.
  • A container in the storage account
  • A blob in a container

The following diagram shows the relationship between these resources.

Diagram of Blob storage architecture

Use the following .NET classes to interact with these resources:

  • CloudStorageAccount: The CloudStorageAccount class represents your Azure storage account. Use this class to authorize access to Blob storage using your account access keys.
  • CloudBlobClient: The CloudBlobClient class provides a point of access to the Blob service in your code.
  • CloudBlobContainer: The CloudBlobContainer class represents a blob container in your code.
  • CloudBlockBlob: The CloudBlockBlob object represents a block blob in your code. Block blobs are made up of blocks of data that can be managed individually.

Code examples

These example code snippets show you how to perform the following with the Azure Blob storage client library for .NET:

Authenticate the client

The code below checks that the environment variable contains a connection string that can be parsed to create a CloudStorageAccount object pointing to the storage account. To check that the connection string is valid, use the TryParse method. If TryParse is successful, it initializes the storageAccount variable and returns true.

Add this code inside the ProcessAsync method:

// Retrieve the connection string for use with the application. The storage 
// connection string is stored in an environment variable on the machine 
// running the application called STORAGE_CONNECTION_STRING. If the 
// environment variable is created after the application is launched in a 
// console or with Visual Studio, the shell or application needs to be closed
// and reloaded to take the environment variable into account.
string storageConnectionString = Environment.GetEnvironmentVariable("STORAGE_CONNECTION_STRING");

// Check whether the connection string can be parsed.
CloudStorageAccount storageAccount;
if (CloudStorageAccount.TryParse(storageConnectionString, out storageAccount))
{
    // If the connection string is valid, proceed with operations against Blob
    // storage here.
    // ADD OTHER OPERATIONS HERE
}
else
{
    // Otherwise, let the user know that they need to define the environment variable.
    Console.WriteLine(
        "A connection string has not been defined in the system environment variables. " +
        "Add an environment variable named 'STORAGE_CONNECTION_STRING' with your storage " +
        "connection string as a value.");
    Console.WriteLine("Press any key to exit the application.");
    Console.ReadLine();
}

Note

To perform the rest of the operations in this article, replace // ADD OTHER OPERATIONS HERE in the code above with the code snippets in the following sections.

Create a container

To create the container, first create an instance of the CloudBlobClient object, which points to Blob storage in your storage account. Next, create an instance of the CloudBlobContainer object, then create the container.

In this case, the code calls the CreateAsync method to create the container. A GUID value is appended to the container name to ensure that it is unique. In a production environment, it's often preferable to use the CreateIfNotExistsAsync method to create a container only if it does not already exist.

Important

Container names must be lowercase. For more information about naming containers and blobs, see Naming and Referencing Containers, Blobs, and Metadata.

// Create the CloudBlobClient that represents the 
// Blob storage endpoint for the storage account.
CloudBlobClient cloudBlobClient = storageAccount.CreateCloudBlobClient();

// Create a container called 'quickstartblobs' and 
// append a GUID value to it to make the name unique.
CloudBlobContainer cloudBlobContainer = 
    cloudBlobClient.GetContainerReference("quickstartblobs" + 
        Guid.NewGuid().ToString());
await cloudBlobContainer.CreateAsync();

Set permissions on a container

Set permissions on the container so that any blobs in the container are public. If a blob is public, it can be accessed anonymously by any client.

// Set the permissions so the blobs are public.
BlobContainerPermissions permissions = new BlobContainerPermissions
{
    PublicAccess = BlobContainerPublicAccessType.Blob
};
await cloudBlobContainer.SetPermissionsAsync(permissions);

Upload blobs to a container

The following code snippet gets a reference to a CloudBlockBlob object by calling the GetBlockBlobReference method on the container created in the previous section. It then uploads the selected local file to the blob by calling the ​Upload​From​FileAsync method. This method creates the blob if it doesn't already exist, and overwrites it if it does.

// Create a file in your local MyDocuments folder to upload to a blob.
string localPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
string localFileName = "QuickStart_" + Guid.NewGuid().ToString() + ".txt";
string sourceFile = Path.Combine(localPath, localFileName);
// Write text to the file.
File.WriteAllText(sourceFile, "Hello, World!");

Console.WriteLine("Temp file = {0}", sourceFile);
Console.WriteLine("Uploading to Blob storage as blob '{0}'", localFileName);

// Get a reference to the blob address, then upload the file to the blob.
// Use the value of localFileName for the blob name.
CloudBlockBlob cloudBlockBlob = cloudBlobContainer.GetBlockBlobReference(localFileName);
await cloudBlockBlob.UploadFromFileAsync(sourceFile);

List the blobs in a container

List the blobs in the container by using the ​List​BlobsSegmentedAsync method. In this case, only one blob has been added to the container, so the listing operation returns just that one blob.

If there are too many blobs to return in one call (by default, more than 5000), then the ​List​BlobsSegmentedAsync method returns a segment of the total result set and a continuation token. To retrieve the next segment of blobs, you provide in the continuation token returned by the previous call, and so on, until the continuation token is null. A null continuation token indicates that all of the blobs have been retrieved. The code shows how to use the continuation token for the sake of best practices.

// List the blobs in the container.
Console.WriteLine("List blobs in container.");
BlobContinuationToken blobContinuationToken = null;
do
{
    var results = await cloudBlobContainer.ListBlobsSegmentedAsync(null, blobContinuationToken);
    // Get the value of the continuation token returned by the listing call.
    blobContinuationToken = results.ContinuationToken;
    foreach (IListBlobItem item in results.Results)
    {
        Console.WriteLine(item.Uri);
    }
} while (blobContinuationToken != null); // Loop while the continuation token is not null.

Download blobs

Download the blob created previously to your local file system by using the ​Download​To​FileAsync method. The example code adds a suffix of "_DOWNLOADED" to the blob name so that you can see both files in local file system.

// Download the blob to a local file, using the reference created earlier.
// Append the string "_DOWNLOADED" before the .txt extension so that you 
// can see both files in MyDocuments.
string destinationFile = sourceFile.Replace(".txt", "_DOWNLOADED.txt");
Console.WriteLine("Downloading blob to {0}", destinationFile);
await cloudBlockBlob.DownloadToFileAsync(destinationFile, FileMode.Create);

Delete a container

The following code cleans up the resources the app created by deleting the entire container using Cloud​Blob​Container.​DeleteAsync. You can also delete the local files if you like.

Console.WriteLine("Press the 'Enter' key to delete the example files, " +
    "example container, and exit the application.");
Console.ReadLine();
// Clean up resources. This includes the container and the two temp files.
Console.WriteLine("Deleting the container");
if (cloudBlobContainer != null)
{
    await cloudBlobContainer.DeleteIfExistsAsync();
}
Console.WriteLine("Deleting the source, and downloaded files");
File.Delete(sourceFile);
File.Delete(destinationFile);

Run the code

This app creates a test file in your local MyDocuments folder and uploads it to Blob storage. The example then lists the blobs in the container and downloads the file with a new name so that you can compare the old and new files.

If you are using Visual Studio as your editor, you can press F5 to run.

Otherwise, navigate to your application directory, then build and run the application.

dotnet build
dotnet run

The output of the example application is similar to the following example:

Azure Blob storage - .NET Quickstart example

Created container 'quickstartblobs33c90d2a-eabd-4236-958b-5cc5949e731f'

Temp file = C:\Users\myusername\Documents\QuickStart_c5e7f24f-a7f8-4926-a9da-96
97c748f4db.txt
Uploading to Blob storage as blob 'QuickStart_c5e7f24f-a7f8-4926-a9da-9697c748f
4db.txt'

Listing blobs in container.
https://storagesamples.blob.core.windows.net/quickstartblobs33c90d2a-eabd-4236-
958b-5cc5949e731f/QuickStart_c5e7f24f-a7f8-4926-a9da-9697c748f4db.txt

Downloading blob to C:\Users\myusername\Documents\QuickStart_c5e7f24f-a7f8-4926
-a9da-9697c748f4db_DOWNLOADED.txt

Press any key to delete the example files and example container.

When you press the Enter key, the application deletes the storage container and the files. Before you delete them, check your MyDocuments folder for the two files. You can open them and observe that they are identical. Copy the blob's URL from the console window and paste it into a browser to view the contents of the blob.

After you've verified the files, hit any key to finish the demo and delete the test files.

Next steps

In this quickstart, you learned how to upload, download, and list blobs using .NET.

To learn how to create a web app that uploads an image to Blob storage, continue to: