Microsoft Azure Blob Storage - Managing Blobs and storage containers from C#

This is the part two of Microsoft Azure Blob Storage where we will look into managing Microsoft Azure Blobs from C# and .NET.

For this blog, we are going to keep this pretty simple. We will create a new .net console application and add two Nugget packages that make it super easy to work with Microsoft Azure Blobs. Include these two Nugget Packages:

  1. WindowsAzure.Storage
  2. Microsoft.WindowsAzure.ConfigurationManager
Obtain Access keys from Azure Portal 


Add it Access Key to App.Config




Include Microsoft Azure Storage namespaces

using Microsoft.Azure;
using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Blob;

Add a Container in Azure Blob Storage from C#


var storageAccount = CloudStorageAccount.Parse(
                CloudConfigurationManager.GetSetting("AzureStorageConnection"));
var blobClient = storageAccount.CreateCloudBlobClient();
var container = blobClient.GetContainerReference("mycontainer");
container.CreateIfNotExists(BlobContainerPublicAccessType.Blob);


The code above obtains storage account by its key, create a connection, obtains a reference for container name mycontainer and finally create the container if it does not already exits.


Upload Image as Block Blob in Azure Storage Container

var storageAccount = CloudStorageAccount.Parse(
                CloudConfigurationManager.GetSetting("AzureStorageConnection"));
var blobClient = storageAccount.CreateCloudBlobClient();
var container = blobClient.GetContainerReference("mycontainer");
container.CreateIfNotExists(BlobContainerPublicAccessType.Blob);

var blockBlob = container.GetBlockBlobReference("imran-images/new/Imran-Duplicate.png");
using (var fileStream = System.IO.File.Open("C:\\Users\\imran\\Downloads\\imran-original.png", System.IO.FileMode.Open))
{
       blockBlob.UploadFromStream(fileStream);

}

The above code gets a reference of block blob with the name Imran-Duplicate.png under imran-images/new folder hierarchy (which does not currently exists and we are going to upload it). Then we open a file steam to an image in our local PC and pass it to Azure api for uploading to the container.

Download Block Blob from Azure Blob Storage Container

var storageAccount = CloudStorageAccount.Parse(
                CloudConfigurationManager.GetSetting("AzureStorageConnection"));
var blobClient = storageAccount.CreateCloudBlobClient();
var container = blobClient.GetContainerReference("mycontainer");
container.CreateIfNotExists(BlobContainerPublicAccessType.Blob);

var blockBlobDownload = container.GetBlockBlobReference("imran-images/Imran-Duplicate.png");
using (var fileStream = System.IO.File.Create("C:\\Users\\imran\\Downloads\\imran-downloaded-image-new.png"))
{
    blockBlobDownload.DownloadToStream(fileStream);
}

The above code download the same uploaded image in the same folder hierarchy from Microsoft Azure Storage Container to local PC.

Listing all Block Blob in a Container 

var storageAccount = CloudStorageAccount.Parse(
                CloudConfigurationManager.GetSetting("AzureStorageConnection"));
var blobClient = storageAccount.CreateCloudBlobClient();
var container = blobClient.GetContainerReference("mycontainer");
container.CreateIfNotExists(BlobContainerPublicAccessType.Blob);

foreach (var blob in container.ListBlobs())
{
         Console.WriteLine(blob.Uri);
}

The above code calls ListBlobs()  method of container instance to list URI of each blobs in the container.


Adding and updating Azure Container Metadata 

var storageAccount = CloudStorageAccount.Parse(
                CloudConfigurationManager.GetSetting("AzureStorageConnection"));
var blobClient = storageAccount.CreateCloudBlobClient();
var container = blobClient.GetContainerReference("mycontainer");
container.CreateIfNotExists(BlobContainerPublicAccessType.Blob);


container.Metadata.Clear(); // clears metadata
// adds a new metadata key-value pair associated with the container
container.Metadata.Add("UserId", "1111");

// adds a new metadata key-value pair associated with the container
container.Metadata.Add("CreatedAt", DateTime.UtcNow.ToString());

 // updates existing metadata key-value pair associated with the container
container.Metadata["UpdatedAt"] = DateTime.UtcNow.ToString();

// Finally save Metadata
container.SetMetadata();

The above code first clears all metadata associated to the contianer, then it adds a new key-value pair of CreateAt key, then it shows updating existing key-value pair by accessing dictionary by its key, finally the call to SetMetadata() updates metadata

List of Metadata associated with a container

var storageAccount = CloudStorageAccount.Parse(
                CloudConfigurationManager.GetSetting("AzureStorageConnection"));
var blobClient = storageAccount.CreateCloudBlobClient();
var container = blobClient.GetContainerReference("mycontainer");
container.CreateIfNotExists(BlobContainerPublicAccessType.Blob);

 // loads container metadata
container.FetchAttributes();
// prints all metadata associated with the container
foreach (var item in container.Metadata)
 {
       Console.WriteLine($"{item.Key} : {item.Value}");
 }

The code in section above prints out all metadata key-value pairs associated to a container.

Copy Block Blob

// Copy Block Blob
var originalImg = container.GetBlobReference("Imran.png");
var copyImg = container.GetBlobReference("Imran-copy.png");
copyImg.BeginStartCopy(originalImg.Uri, (obj) => Console.WriteLine("I am in love"), null);

Above code shows copy blobs from one container to another (a very common use case).

That's it, we have seen how we can create and manage Microsoft Azure Containers as well as Blobs.

Comments

  1. I am really impressed with the way of writing of this blog regarding microsoft azure cloud migration services. Thank you for sharing.
    azure cloud migration services

    ReplyDelete
  2. You have provided a richly informative article about Microsoft Azure Blob Storage. It is a beneficial article for me and also helpful for others. Thanks for sharing this information here. oracle fusion financials

    ReplyDelete
  3. I loved the information given above, I appreciate the writing. Enhance your learning experience with our top-notch online home tuition classes for Class 11.
    For more info Contact us: +91-9654271931, +971-505593798 or visit online tutoring sites for class 11

    ReplyDelete
  4. Thank you so much for taking the time to share this wonderful article. Join Ziyyara's online English tuition classes for a personalized learning experience. Master the language, improve fluency, and boost your confidence in English communication with expert guidance and interactive sessions.
    For more info visit Online english tuition

    ReplyDelete
  5. 33B74471D2IsraelF5F006842125 November 2024 at 05:53

    32FF716179
    show

    ReplyDelete
  6. D21611D96CChaseD76EF5EAA126 November 2024 at 02:22

    CB21F605F3
    skype şov

    ReplyDelete

Post a Comment

Popular posts from this blog

Implementing Basic and JWT Token authentication with C# .NET

.NET Core 3 officially comes to Windows IoT Core

Setting up Free Custom Domain on Microsoft Azure Web App Service

Setting up CI and CD pipeline in Azure DevOps for ASP.NET Core and Azure Web Apps

Microsoft Azure DevOps : A Complete CI & CD solution in the cloud

Securing Powershell Scripts with Code-Signing Certificate

Understanding Powershell ExecutionPolicy and securing Powershell CmdLets/Scripts with Code-Signing Certificate

Xamrin Android Push Notification using Firebase Cloud Messaging

Fundamental of Powershell Scripting