How do I download a file from Azure Blob Storage to a .NET application?

This technique should work for any .NET Core application.

Add the following Nuget packages:

  1. Azure.Identity
  2. Azure.Storage.Blobs

Add a file to your project called BlobService.cs and paste the contents of this file.

Next, instantiate and authenticate to your container. In this example, I am using the Connection String method. I have logged into the Azure Portal, and copied the connection string from the Access Keys page of the Storage Account. Click here for more information about Access Keys.

Note: For production scenarios, you will want to register your application and use a client id/secret to authenticate. See here for details.

string BlobConnectionString = 
    "DefaultEndpointsProtocol=https;AccountName=StevesStorageAccount;AccountKey=REDACTED==;EndpointSuffix=core.windows.net";

Emrick.CStringBlobService blobService =
    new Emrick.CStringBlobService(BlobConnectionString, "file-uploads")

Note that the constructor takes both the connection string AND the name of the container.

Next, we simply call the GetContentsOfFolder method. This method returns a List of file names in the specified folder path.

List<string> listOfFiles = 
    blobService.GetContentsOfFolder(filePath);

In order to download a file, call the GetFile method. This will return a stream of the file contents.

System.IO.Stream fileData = blobService.GetFile("2023 Resume.pdf");

Once you have the file in a stream, you can save it locally or display it to your user. For example, to save locally, simply:

using (System.IO.Stream file = File.Create("C:\\2023 Resume.pdf"))
{
    fileData.CopyTo(file);
}

Comments

Popular posts from this blog

How to add Bootstrap to a Blazor application