Get started with Azure blob storage and Visual Studio Connected Services (ASP.NET)

Tip

Manage Azure Blob Storage resources with Microsoft Azure Storage Explorer

Microsoft Azure Storage Explorer is a free, standalone app from Microsoft that enables you to manage Azure Blob Storage resources. Using Microsoft Azure Storage Explorer, you can visually create, read, update, and delete blob containers and blobs, as well as manage access to your blobs containers and blobs.

Overview

Azure blob storage is a service that stores unstructured data in the cloud as objects/blobs. Blob storage can store any type of text or binary data, such as a document, media file, or application installer. Blob storage is also referred to as object storage.

This tutorial shows how to write ASP.NET code for some common scenarios using Azure blob storage. Scenarios include creating a blob container, and uploading, listing, downloading, and deleting blobs.

Prerequisites

What is Blob Storage?

Azure Blob storage is a service for storing large amounts of unstructured object data, such as text or binary data, that can be accessed from anywhere in the world via HTTP or HTTPS. You can use Blob storage to expose data publicly to the world, or to store application data privately.

Common uses of Blob storage include:

  • Serving images or documents directly to a browser
  • Storing files for distributed access
  • Streaming video and audio
  • Storing data for backup and restore, disaster recovery, and archiving
  • Storing data for analysis by an on-premises or Azure-hosted service

Blob service concepts

The Blob service contains the following components:

Blob architecture

  • Storage Account: All access to Azure Storage is done through a storage account. This storage account can be a General-purpose storage account or a Blob storage account which is specialized for storing objects/blobs. See About Azure storage accounts for more information.
  • Container: A container provides a grouping of a set of blobs. All blobs must be in a container. An account can contain an unlimited number of containers. A container can store an unlimited number of blobs. Note that the container name must be lowercase.
  • Blob: A file of any type and size. Azure Storage offers three types of blobs: block blobs, page blobs, and append blobs.

    Block blobs are ideal for storing text or binary files, such as documents and media files. Append blobs are similar to block blobs in that they are made up of blocks, but they are optimized for append operations, so they are useful for logging scenarios. A single block blob can contain up to 50,000 blocks of up to 100 MB each, for a total size of slightly more than 4.75 TB (100 MB X 50,000). A single append blob can contain up to 50,000 blocks of up to 4 MB each, for a total size of slightly more than 195 GB (4 MB X 50,000).

    Page blobs can be up to 1 TB in size, and are more efficient for frequent read/write operations. Azure Virtual Machines use page blobs as OS and data disks.

    For details about naming containers and blobs, see Naming and Referencing Containers, Blobs, and Metadata.

Create an Azure storage account

The easiest way to create your first Azure storage account is by using the Azure Portal. To learn more, see Create a storage account.

You can also create an Azure storage account by using Azure PowerShell, Azure CLI, or the Storage Resource Provider Client Library for .NET.

Set up the development environment

This section walks you setting up your development environment, including creating an ASP.NET MVC app, adding a Connected Services connection, adding a controller, and specifying the required namespace directives.

Create an ASP.NET MVC app project

  1. Open Visual Studio.

  2. Select File->New->Project from the main menu

  3. On the New Project dialog, specify the options as highlighted in the following figure:

    Create ASP.NET project

  4. Select OK.

  5. On the New ASP.NET Project dialog, specify the options as highlighted in the following figure:

    Specify MVC

  6. Select OK.

Use Connected Services to connect to an Azure storage account

  1. In the Solution Explorer, right-click the project, and from the context menu, select Add->Connected Service.

  2. On the Add Connected Service dialog, select Azure Storage, and then select Configure.

    Connected Service dialog

  3. On the Azure Storage dialog, select the desired Azure storage account with which you want to work, and select Add.

Create an MVC controller

  1. In the Solution Explorer, right-click Controllers, and, from the context menu, select Add->Controller.

    Add a controller to an ASP.NET MVC app

  2. On the Add Scaffold dialog, select MVC 5 Controller - Empty, and select Add.

    Specify MVC controller type

  3. On the Add Controller dialog, name the controller BlobsController, and select Add.

    Name the MVC controller

  4. Add the following using directives to the BlobsController.cs file:

    using Microsoft.Azure;
    using Microsoft.WindowsAzure.Storage;
    using Microsoft.WindowsAzure.Storage.Auth;
    using Microsoft.WindowsAzure.Storage.Blob;
    

Create a blob container

A blob container is a nested hierarchy of blobs and folders. The following steps illustrate how to create a blob container:

Note

The code in this section assumes that you have completed the steps in the section, Set up the development environment.

  1. Open the BlobsController.cs file.

  2. Add a method called CreateBlobContainer that returns an ActionResult.

    public ActionResult CreateBlobContainer()
    {
        // The code in this section goes here.
    
        return View();
    }
    
  3. Within the CreateBlobContainer method, get a CloudStorageAccount object that represents your storage account information. Use the following code to get the storage connection string and storage account information from the Azure service configuration. (Change <storage-account-name> to the name of the Azure storage account you're accessing.)

    CloudStorageAccount storageAccount = CloudStorageAccount.Parse(
       CloudConfigurationManager.GetSetting("<storage-account-name>_AzureStorageConnectionString"));
    
  4. Get a CloudBlobClient object represents a blob service client.

    CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
    
  5. Get a CloudBlobContainer object that represents a reference to the desired blob container name. The CloudBlobClient.GetContainerReference method does not make a request against blob storage. The reference is returned whether or not the blob container exists.

    CloudBlobContainer container = blobClient.GetContainerReference("test-blob-container");
    
  6. Call the CloudBlobContainer.CreateIfNotExists method to create the container if it does not yet exist. The CloudBlobContainer.CreateIfNotExists method returns true if the container does not exist, and is successfully created. Otherwise, false is returned.

    ViewBag.Success = container.CreateIfNotExists();
    
  7. Update the ViewBag with the name of the blob container.

    ViewBag.BlobContainerName = container.Name;
    
  8. In the Solution Explorer, expand the Views folder, right-click Blobs, and from the context menu, select Add->View.

  9. On the Add View dialog, enter CreateBlobContainer for the view name, and select Add.

  10. Open CreateBlobContainer.cshtml, and modify it so that it looks like the following code snippet:

    @{
        ViewBag.Title = "Create Blob Container";
    }
    
    <h2>Create Blob Container results</h2>
    
    Creation of @ViewBag.BlobContainerName @(ViewBag.Success == true ? "succeeded" : "failed")
    
  11. In the Solution Explorer, expand the Views->Shared folder, and open _Layout.cshtml.

  12. After the last Html.ActionLink, add the following Html.ActionLink:

    <li>@Html.ActionLink("Create blob container", "CreateBlobContainer", "Blobs")</li>
    
  13. Run the application, and select Create Blob Container to see results similar to the following screen shot:

    Create blob container

    As mentioned previously, the CloudBlobContainer.CreateIfNotExists method returns true only when the container doesn't exist and is created. Therefore, if you run the app when the container exists, the method returns false. To run the app multiple times, you must delete the container before running the app again. Deleting the container can be done via the CloudBlobContainer.Delete method. You can also delete the container using the Azure portal or the Microsoft Azure Storage Explorer.

Upload a blob into a blob container

Once you've created a blob container, you can upload files into that container. This section walks you through uploading a local file to a blob container. The steps assume you've created a blob container named test-blob-container.

Note

The code in this section assumes that you have completed the steps in the section, Set up the development environment.

  1. Open the BlobsController.cs file.

  2. Add a method called UploadBlob that returns an EmptyResult.

    public EmptyResult UploadBlob()
    {
        // The code in this section goes here.
    
        return new EmptyResult();
    }
    
  3. Within the UploadBlob method, get a CloudStorageAccount object that represents your storage account information. Use the following code to get the storage connection string and storage account information from the Azure service configuration: (Change <storage-account-name> to the name of the Azure storage account you're accessing.)

    CloudStorageAccount storageAccount = CloudStorageAccount.Parse(
       CloudConfigurationManager.GetSetting("<storage-account-name>_AzureStorageConnectionString"));
    
  4. Get a CloudBlobClient object represents a blob service client.

    CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
    
  5. Get a CloudBlobContainer object that represents a reference to the blob container name.

    CloudBlobContainer container = blobClient.GetContainerReference("test-blob-container");
    
  6. As explained earlier, Azure storage supports different blob types. To retrieve a reference to a page blob, call the CloudBlobContainer.GetPageBlobReference method. To retrieve a reference to a block blob, call the CloudBlobContainer.GetBlockBlobReference method. Usually, block blob is the recommended type to use. (Change * to the name you want to give the blob once uploaded.)

    CloudBlockBlob blob = container.GetBlockBlobReference(<blob-name>);
    
  7. Once you have a blob reference, you can upload any data stream to it by calling the blob reference object's UploadFromStream method. The UploadFromStream method creates the blob if it doesn't exist, or overwrites it if it does exist. (Change <file-to-upload> to a fully qualified path to the file you want to upload.)

    using (var fileStream = System.IO.File.OpenRead(<file-to-upload>))
    {
        blob.UploadFromStream(fileStream);
    }
    
  8. In the Solution Explorer, expand the Views folder, right-click Blobs, and from the context menu, select Add->View.

  9. In the Solution Explorer, expand the Views->Shared folder, and open _Layout.cshtml.

  10. After the last Html.ActionLink, add the following Html.ActionLink:

    <li>@Html.ActionLink("Upload blob", "UploadBlob", "Blobs")</li>
    
  11. Run the application, and select Upload blob.

The section - List the blobs in a blob container - illustrates how to list the blobs in a blob container.

List the blobs in a blob container

This section illustrates how to list the blobs in a blob container. The sample code references the test-blob-container created in the section, Create a blob container.

Note

The code in this section assumes that you have completed the steps in the section, Set up the development environment.

  1. Open the BlobsController.cs file.

  2. Add a method called ListBlobs that returns an ActionResult.

    public ActionResult ListBlobs()
    {
        // The code in this section goes here.
    
        return View();
    }
    
  3. Within the ListBlobs method, get a CloudStorageAccount object that represents your storage account information. Use the following code to get the storage connection string and storage account information from the Azure service configuration: (Change <storage-account-name> to the name of the Azure storage account you're accessing.)

    CloudStorageAccount storageAccount = CloudStorageAccount.Parse(
       CloudConfigurationManager.GetSetting("<storage-account-name>_AzureStorageConnectionString"));
    
  4. Get a CloudBlobClient object represents a blob service client.

    CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
    
  5. Get a CloudBlobContainer object that represents a reference to the blob container name.

    CloudBlobContainer container = blobClient.GetContainerReference("test-blob-container");
    
  6. To list the blobs in a blob container, use the CloudBlobContainer.ListBlobs method. The CloudBlobContainer.ListBlobs method returns an IListBlobItem object that you cast to a CloudBlockBlob, CloudPageBlob, or CloudBlobDirectory object. The following code snippet enumerates all the blobs in a blob container. Each blob is cast to the appropriate object based on its type, and its name (or URI in the case of a CloudBlobDirectory) is added to a list.

    List<string> blobs = new List<string>();
    
    foreach (IListBlobItem item in container.ListBlobs(null, false))
    {
        if (item.GetType() == typeof(CloudBlockBlob))
        {
            CloudBlockBlob blob = (CloudBlockBlob)item;
            blobs.Add(blob.Name);
        }
        else if (item.GetType() == typeof(CloudPageBlob))
        {
            CloudPageBlob blob = (CloudPageBlob)item;
            blobs.Add(blob.Name);
        }
        else if (item.GetType() == typeof(CloudBlobDirectory))
        {
            CloudBlobDirectory dir = (CloudBlobDirectory)item;
            blobs.Add(dir.Uri.ToString());
        }
    }
    
    return View(blobs);
    

    In addition to blobs, blob containers can contain directories. Let's suppose you have a blob container called test-blob-container with the following hierarchy:

     foo.png
     dir1/bar.png
     dir2/baz.png
    

    Using the preceding code example, the blobs string list contains values similar to the following:

     foo.png
     <storage-account-url>/test-blob-container/dir1
     <storage-account-url>/test-blob-container/dir2
    

    As you can see, the list includes only the top-level entities; not the nested ones (bar.png and baz.png). To list all the entities within a blob container, you must call the CloudBlobContainer.ListBlobs method and pass true for the useFlatBlobListing parameter.

    ...
    foreach (IListBlobItem item in container.ListBlobs(useFlatBlobListing:true))
    ...
    

    Setting the useFlatBlobListing parameter to true returns a flat listing of all entities in the blob container, and yields the following results:

     foo.png
     dir1/bar.png
     dir2/baz.png
    
  7. In the Solution Explorer, expand the Views folder, right-click Blobs, and from the context menu, select Add->View.

  8. On the Add View dialog, enter ListBlobs for the view name, and select Add.

  9. Open ListBlobs.cshtml, and modify it so that it looks like the following code snippet:

    @model List<string>
    @{
        ViewBag.Title = "List blobs";
    }
    
    <h2>List blobs</h2>
    
    <ul>
        @foreach (var item in Model)
        {
        <li>@item</li>
        }
    </ul>
    
  10. In the Solution Explorer, expand the Views->Shared folder, and open _Layout.cshtml.

  11. After the last Html.ActionLink, add the following Html.ActionLink:

    <li>@Html.ActionLink("List blobs", "ListBlobs", "Blobs")</li>
    
  12. Run the application, and select List blobs to see results similar to the following screen shot:

    Blob listing

Download blobs

This section illustrates how to download a blob and either persist it to local storage or read the contents into a string. The sample code references the test-blob-container created in the section, Create a blob container.

  1. Open the BlobsController.cs file.

  2. Add a method called DownloadBlob that returns an ActionResult.

    public EmptyResult DownloadBlob()
    {
        // The code in this section goes here.
    
        return new EmptyResult();
    }
    
  3. Within the DownloadBlob method, get a CloudStorageAccount object that represents your storage account information. Use the following code to get the storage connection string and storage account information from the Azure service configuration: (Change <storage-account-name> to the name of the Azure storage account you're accessing.)

    CloudStorageAccount storageAccount = CloudStorageAccount.Parse(
       CloudConfigurationManager.GetSetting("<storage-account-name>_AzureStorageConnectionString"));
    
  4. Get a CloudBlobClient object represents a blob service client.

    CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
    
  5. Get a CloudBlobContainer object that represents a reference to the blob container name.

    CloudBlobContainer container = blobClient.GetContainerReference("test-blob-container");
    
  6. Get a blob reference object by calling CloudBlobContainer.GetBlockBlobReference or CloudBlobContainer.GetPageBlobReference method. (Change <blob-name> to the name of the blob you are downloading.)

    CloudBlockBlob blob = container.GetBlockBlobReference(<blob-name>);
    
  7. To download a blob, use the CloudBlockBlob.DownloadToStream or CloudPageBlob.DownloadToStream method, depending on the blob type. The following code snippet uses the CloudBlockBlob.DownloadToStream method to transfer a blob's contents to a stream object that is then persisted to a local file: (Change <local-file-name> to the fully qualified file name representing where you want the blob downloaded.)

    using (var fileStream = System.IO.File.OpenWrite(<local-file-name>))
    {
        blob.DownloadToStream(fileStream);
    }
    
  8. In the Solution Explorer, expand the Views->Shared folder, and open _Layout.cshtml.

  9. After the last Html.ActionLink, add the following Html.ActionLink:

    <li>@Html.ActionLink("Download blob", "DownloadBlob", "Blobs")</li>
    
  10. Run the application, and select Download blob to download the blob. The blob specified in the CloudBlobContainer.GetBlockBlobReference method call downloads to the location you specify in the File.OpenWrite method call.

Delete blobs

The following steps illustrate how to delete a blob:

Note

The code in this section assumes that you have completed the steps in the section, Set up the development environment.

  1. Open the BlobsController.cs file.

  2. Add a method called DeleteBlob that returns an ActionResult.

    public EmptyResult DeleteBlob()
    {
        // The code in this section goes here.
    
        return new EmptyResult();
    }
    
  3. Get a CloudStorageAccount object that represents your storage account information. Use the following code to get the storage connection string and storage account information from the Azure service configuration: (Change <storage-account-name> to the name of the Azure storage account you're accessing.)

    CloudStorageAccount storageAccount = CloudStorageAccount.Parse(
       CloudConfigurationManager.GetSetting("<storage-account-name>_AzureStorageConnectionString"));
    
  4. Get a CloudBlobClient object represents a blob service client.

    CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
    
  5. Get a CloudBlobContainer object that represents a reference to the blob container name.

    CloudBlobContainer container = blobClient.GetContainerReference("test-blob-container");
    
  6. Get a blob reference object by calling CloudBlobContainer.GetBlockBlobReference or CloudBlobContainer.GetPageBlobReference method. (Change <blob-name> to the name of the blob you are deleting.)

    CloudBlockBlob blob = container.GetBlockBlobReference(<blob-name>);
        ```
    
    
  7. To delete a blob, use the Delete method.

    blob.Delete();
    
  8. In the Solution Explorer, expand the Views->Shared folder, and open _Layout.cshtml.

  9. After the last Html.ActionLink, add the following Html.ActionLink:

    <li>@Html.ActionLink("Delete blob", "DeleteBlob", "Blobs")</li>
    
  10. Run the application, and select Delete blob to delete the blob specified in the CloudBlobContainer.GetBlockBlobReference method call.

Next steps

View more feature guides to learn about additional options for storing data in Azure.