DEV Community

Chandra Mohan Jha
Chandra Mohan Jha

Posted on

Download blob from azure using Azure.Storage.Blobs

We can store blobs in Azure platform in C# using Azure.Storage.Blobs. Previously we had Microsoft.WindowsAzure.Storage for this but they rewrote it. Don't ask me why. As Microsoft.WindowsAzure.Storage is deprecated now and we needed to access Azure to read blobs, we have no other option rather than using new Azure.Storage.Blobs. If you search docs to use Azure in C#, the results will be flooded with Microsoft.WindowsAzure.Storage. If you ask specifically about new APIs, you will get mostly Microsoft docs links. I find Microsoft docs unusable🤭. And if you are like me, you are welcome to follow the article.

First thing first: install NuGet package

Install NuGet package Azure.Storage.Blobs. At the time of writing this, the latest version is 12.8.0.

Import library

using Azure.Storage.Blobs;

Get connection string

I assume you have Azure account and thus connection string to connect to Azure Blob Storage. Store this in a variable or constant based on your need.

const string CONN_STRING = <connection_string_from_azure_portal>
const string BLOB_CONTAINER = <blob_container_name>
Enter fullscreen mode Exit fullscreen mode

Now the final thing

I will download the blob to a local file and read it.

string filePath = "<optional_path/file_name.extension>";
var blobClient = new BlobClient(CONN_STRING, BLOB_CONTAINER, <blob_uri>);
var result =  blobClient.DownloadTo(filePath); // file is downloaded
// check file download was success or not
if (result.Status == 206 || result.Status == 200)
{
  // You would be knowing this by now
  using (StreamReader r = new StreamReader(filePath))
  {
    string content = r.ReadToEnd(); // I don't know what you want to do with this
  }
}
Enter fullscreen mode Exit fullscreen mode

That's it. I hope it would be helpful to you. 🙂

Top comments (0)