Quickstart: Azure Blob Storage client library v12 for .NET

Get started with the Azure Blob Storage client library v12 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.

The examples in this quickstart show you how to use the Azure Blob Storage client library v12 for .NET to:

Additional resources:

Prerequisites

Setting up

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

Create the project

Create a .NET Core application named BlobQuickstartV12.

  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 BlobQuickstartV12. This command creates a simple "Hello World" C# project with a single source file: Program.cs.

    dotnet new console -n BlobQuickstartV12
    
  2. Switch to the newly created BlobQuickstartV12 directory.

    cd BlobQuickstartV12
    
  3. In side the BlobQuickstartV12 directory, create another directory called data. This is where the blob data files will be created and stored.

    mkdir data
    

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 Azure.Storage.Blobs

Set up the app framework

From the project directory:

  1. Open the Program.cs file in your editor.

  2. Remove the Console.WriteLine("Hello World!"); statement.

  3. Add using directives.

  4. Update the Main method declaration to support async.

    Here's the code:

    using Azure.Storage.Blobs;
    using Azure.Storage.Blobs.Models;
    using System;
    using System.IO;
    using System.Threading.Tasks;
    
    namespace BlobQuickstartV12
    {
        class Program
        {
            static async Task Main()
            {
            }
        }
    }
    

Copy your credentials from the Azure portal

When the sample application makes a request to Azure Storage, it must be authorized. To authorize a request, add your storage account credentials to the application as a connection string. To view your storage account credentials, follow these steps:

  1. Sign in to the Azure portal.

  2. Locate your storage account.

  3. In the storage account menu pane, under Security + networking, select Access keys. Here, you can view the account access keys and the complete connection string for each key.

    Screenshot that shows where the access key settings are in the Azure portal

  4. In the Access keys pane, select Show keys.

  5. In the key1 section, locate the Connection string value. Select the Copy to clipboard icon to copy the connection string. You will add the connection string value to an environment variable in the next section.

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

Configure your storage connection string

After you copy the 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.

Windows

setx AZURE_STORAGE_CONNECTION_STRING "<yourconnectionstring>"

After you add the environment variable in Windows, you must start a new instance of the command window.

Linux

export AZURE_STORAGE_CONNECTION_STRING="<yourconnectionstring>"

macOS

export AZURE_STORAGE_CONNECTION_STRING="<yourconnectionstring>"

Restart programs

After you add the environment variable, restart any running programs that will need to read the environment variable. For example, restart your development environment or editor before you continue.

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 the 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:

  • BlobServiceClient: The BlobServiceClient class allows you to manipulate Azure Storage resources and blob containers.
  • BlobContainerClient: The BlobContainerClient class allows you to manipulate Azure Storage containers and their blobs.
  • BlobClient: The BlobClient class allows you to manipulate Azure Storage blobs.

Code examples

The sample code snippets in the following sections show you how to perform basic data operations with the Azure Blob Storage client library for .NET.

Get the connection string

The code below retrieves the connection string for the storage account from the environment variable created in the Configure your storage connection string section.

Add this code inside the Main method:

Console.WriteLine("Azure Blob Storage v12 - .NET quickstart sample\n");

// 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 AZURE_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 connectionString = Environment.GetEnvironmentVariable("AZURE_STORAGE_CONNECTION_STRING");

Create a container

Decide on a name for the new container. The code below appends a GUID value to the container name to ensure that it is unique.

Important

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

Create an instance of the BlobServiceClient class. Then, call the CreateBlobContainerAsync method to create the container in your storage account.

Add this code to the end of the Main method:

// Create a BlobServiceClient object which will be used to create a container client
BlobServiceClient blobServiceClient = new BlobServiceClient(connectionString);

//Create a unique name for the container
string containerName = "quickstartblobs" + Guid.NewGuid().ToString();

// Create the container and return a container client object
BlobContainerClient containerClient = await blobServiceClient.CreateBlobContainerAsync(containerName);

Upload a blob to a container

The following code snippet:

  1. Creates a text file in the local data directory.
  2. Gets a reference to a BlobClient object by calling the GetBlobClient method on the container from the Create a container section.
  3. Uploads the local text file to the blob by calling the UploadAsync method. This method creates the blob if it doesn't already exist, and overwrites it if it does.

Add this code to the end of the Main method:

// Create a local file in the ./data/ directory for uploading and downloading
string localPath = "./data/";
string fileName = "quickstart" + Guid.NewGuid().ToString() + ".txt";
string localFilePath = Path.Combine(localPath, fileName);

// Write text to the file
await File.WriteAllTextAsync(localFilePath, "Hello, World!");

// Get a reference to a blob
BlobClient blobClient = containerClient.GetBlobClient(fileName);

Console.WriteLine("Uploading to Blob storage as blob:\n\t {0}\n", blobClient.Uri);

// Upload data from the local file
await blobClient.UploadAsync(localFilePath, true);

List blobs in a container

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

Add this code to the end of the Main method:

Console.WriteLine("Listing blobs...");

// List all blobs in the container
await foreach (BlobItem blobItem in containerClient.GetBlobsAsync())
{
    Console.WriteLine("\t" + blobItem.Name);
}

Download a blob

Download the previously created blob by calling the DownloadToAsync method. The example code adds a suffix of "DOWNLOADED" to the file name so that you can see both files in local file system.

Add this code to the end of the Main method:

// Download the blob to a local file
// Append the string "DOWNLOADED" before the .txt extension 
// so you can compare the files in the data directory
string downloadFilePath = localFilePath.Replace(".txt", "DOWNLOADED.txt");

Console.WriteLine("\nDownloading blob to\n\t{0}\n", downloadFilePath);

// Download the blob's contents and save it to a file
await blobClient.DownloadToAsync(downloadFilePath);

Delete a container

The following code cleans up the resources the app created by deleting the entire container by using DeleteAsync. It also deletes the local files created by the app.

The app pauses for user input by calling Console.ReadLine before it deletes the blob, container, and local files. This is a good chance to verify that the resources were actually created correctly, before they are deleted.

Add this code to the end of the Main method:

// Clean up
Console.Write("Press any key to begin clean up");
Console.ReadLine();

Console.WriteLine("Deleting blob container...");
await containerClient.DeleteAsync();

Console.WriteLine("Deleting the local source and downloaded files...");
File.Delete(localFilePath);
File.Delete(downloadFilePath);

Console.WriteLine("Done");

Run the code

This app creates a test file in your local data 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.

Navigate to your application directory, then build and run the application.

dotnet build
dotnet run

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

Azure Blob Storage v12 - .NET quickstart sample

Uploading to Blob storage as blob:
         https://mystorageacct.blob.core.windows.net/quickstartblobs60c70d78-8d93-43ae-954d-8322058cfd64/quickstart2fe6c5b4-7918-46cb-96f4-8c4c5cb2fd31.txt

Listing blobs...
        quickstart2fe6c5b4-7918-46cb-96f4-8c4c5cb2fd31.txt

Downloading blob to
        ./data/quickstart2fe6c5b4-7918-46cb-96f4-8c4c5cb2fd31DOWNLOADED.txt

Press any key to begin clean up
Deleting blob container...
Deleting the local source and downloaded files...
Done

Before you begin the clean up process, check your data folder for the two files. You can open them and observe that they are identical.

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

Next steps

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

To see Blob storage sample apps, continue to: