Skip to content

Latest commit

 

History

History
456 lines (310 loc) · 18.9 KB

vs-storage-aspnet-getting-started-blobs.md

File metadata and controls

456 lines (310 loc) · 18.9 KB
title description services documentationcenter author manager editor ms.assetid ms.service ms.workload ms.tgt_pltfrm ms.devlang ms.topic ms.date ms.author
Get started with Azure blob storage and Visual Studio Connected Services (ASP.NET) | Microsoft Docs
How to get started using Azure blob storage in an ASP.NET project in Visual Studio after connecting to a storage account using Visual Studio Connected Services
storage
TomArcher
douge
b3497055-bef8-4c95-8567-181556b50d95
storage
web
vs-getting-started
na
article
12/02/2016
tarcher

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

[!INCLUDE storage-try-azure-tools-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

[!INCLUDE storage-blob-concepts-include]

[!INCLUDE storage-create-account-include]

[!INCLUDE storage-development-environment-include]

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.

  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.

    @{
        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. You will see results similar to those shown in 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 will return 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 how to upload a local file to a blob container. The steps assume you've created a blob container named test-blob-container. You'll need to change that to the name of your blob container.

  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 next section will illustrate 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.

  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, casting the returned object to the appropriate object based on its type, and adds the name (or URI in the case of a CloudBlobDirectory) to a list that can be displayed.

    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). In order 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.

    @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. You will see results similar to those shown in the following screen shot.

    Blob listing

Download blobs

The following steps illustrate 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 specify 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.

  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.