Microsoft Azure – Storage – Part 4 – Download files with a .NET application

In the third part of the Microsoft Azure Storage series we have extended our .NET application to list the contents of a container.  Today we will add a method to our application to download files from the storage container.

Download blobs from the Microsoft Azure storage

Create the DownloadFile method in the Azure Helper

  • Open the Azure_Helper.cs file in the Azure_Helper project
  • Add a new method to the class
/// <summary>
/// Downloads a blob from the storage container and saves it in the file system
/// </summary>
/// <param name="sContainerPath"></param>
/// <param name="sBlobName"></param>
/// <param name="sTargetFilePath"></param>
public void DownloadFile(string sContainerPath, string sBlobName, string sTargetFilePath) {

    // Create the blob client.
    CloudBlobClient blobClient = _storageAccount.CreateCloudBlobClient();

    // Retrieve reference to a previously created container.
    CloudBlobContainer container = blobClient.GetContainerReference(sContainerPath);

    // Retrieve reference to a blob
    CloudBlockBlob blockBlob = container.GetBlockBlobReference(sBlobName);

    // Save blob contents to a file.
    using (var fileStream = System.IO.File.OpenWrite(sTargetFilePath)) {
        blockBlob.DownloadToStream(fileStream);
    }

}

This method will download the file from the Microsoft Azure storage and save it on a disk.

Add code to the console application to call the DownloadFile method

  • Open the Program.cs file in the Azure_ConsoleApplication
  • Add the following lines to the end of the Main method
string sTargetFilePath = @"D:\MediaFiles\Audio\DownloadedMusic.wav";

// Download the file from the Azure storage and save it
azureHelper.DownloadFile(sContainerPath, sBlobName, sTargetFilePath);

Test your application

Run your application. A new file should appear in the specified target folder.

In the next article of the Azure storage series we will learn how to delete a blob from the storage container.

Join the Conversation

2 Comments

Leave a comment

Your email address will not be published. Required fields are marked *