This post was most recently updated on May 7th, 2019
In this article, we are going to demonstrate how to download a file from Azure Blob Storage.
Since Blob resides inside the container and the container resides inside Azure Storage Account, we need to have access to an Azure Storage Account.
It can be done by getting the Storage Account as the connection string. We can retrieve Azure Storage Account connection string, using Azure Storage Account class.
Install following NuGet packages in your project:
1. Install-Package WindowsAzure.Storage -Version 9.3.3
2. Install-Package Microsoft.Azure.Storage.Blob -Version 10.0.1
Add following namespace to work with Azure Storage:
1. using Microsoft.Azure;
2. using Microsoft.WindowsAzure.Storage;
3. using Microsoft.WindowsAzure.Storage.Blob;
Create connection in web config:
1 2 3 4 |
<appSettings> <add key=”StorageConnectionString” value=”DefaultEndpointsProtocol=https;AccountName=hr67zeymbbyjksawinvm;AccountKey=*****;EndpointSuffix=core.windows.net” /> <add key=”Container” value=””mytestcontainer””/> </appSettings> |
To download from Blob follow following steps:
1. Create a connection to storage account.
2. Create Blob client to retrieve containers and Blobs in the storage.
3. Download file from blob to the local machine.
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
public void DownloadFileFromBlob(string fileName) { string folderName =”DatabaseBackupFiles”; var storageAccount = CloudStorageAccount.Parse(ConfigurationManager.AppSettings.Get(“StorageConnectionString”).ToString()); var blobClient = storageAccount.CreateCloudBlobClient(); // Get Blob Container var container = blobClient.GetContainerReference(ConfigurationManager.AppSettings.Get(“Container”).ToString()); // Get reference to blob (binary content) var pageBlob = container.GetPageBlobReference(fileName); string directoryPath = Server.MapPath(folderName).ToString(); string filePath = directoryPath + “\\” + fileName; if (!Directory.Exists(directoryPath)) { Directory.CreateDirectory(directoryPath); } blockBlob.DownloadToFile(filePath, FileMode.OpenOrCreate); } |
Look into Microsoft Azure Storage Explorer for Container and Connection string: