Azure - Manage Blob Storage - Part #10 - Complete Example with Code


Problem Definition

How to Manage a blob container using C# in Azure(Complete Code).

Prerequisites

  • Access to Azure Portal - http://portal.azure.com
  • Azure General Purpose Storage Account
  • Microsoft Visual Studio(For this demo used Visual Studio Community for Mac)

Use following code in your "BlobStorageContainer.cs"




using System;

using System.Collections.Generic;
//Required for Azure
using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Blob;


namespace AzureWorkshop
{
    public class BlobStorageContainer
    {
        public CloudBlobContainer CloudBlobContainer
        {
            get;
            set;
        }
        public BlobStorageContainer(string containerName)
        {
                 string storageConnectionString = @"DefaultEndpointsProtocol=https;AccountName=****;AccountKey=****;EndpointSuffix=core.windows.net";
            CloudStorageAccount cloudStorageAccount = CloudStorageAccount.Parse(storageConnectionString);
            CloudBlobClient cloudBlobClient = cloudStorageAccount.CreateCloudBlobClient();
            CloudBlobContainer = cloudBlobClient.GetContainerReference(containerName);
        }
        public bool Create()
        {
            if (!CloudBlobContainer.CreateIfNotExists())
            {
                return false;
            }
            return true;
        }
        public bool Delete()
        {
            if (!CloudBlobContainer.DeleteIfExists())
            {
                return false;
            }
            return true;
        }

        public bool Exists(string containerName)
        {
            if (!CloudBlobContainer.Exists())
            {
                return false;
            }
            return true;
        }
        public bool ListAllBlobs(string containerName)
        {
            if (!CloudBlobContainer.Exists())
            {
                return false;
            }
            // Loop over items within the container and output the length and URI.
            foreach (IListBlobItem item in CloudBlobContainer.ListBlobs(null, false))
            {
                if (item.GetType() == typeof(CloudBlockBlob))
                {
                    CloudBlockBlob blob = (CloudBlockBlob)item;
                    Console.WriteLine($"Block Blob({blob.Name}) of length {blob.Properties.Length}: {blob.Uri}");
                }
                else if (item.GetType() == typeof(CloudPageBlob))
                {
                    CloudPageBlob pageBlob = (CloudPageBlob)item;
                    Console.WriteLine($"Page Blob({pageBlob.Name}) of length {pageBlob.Properties.Length}: {pageBlob.Uri}");
                }
                else if (item.GetType() == typeof(CloudBlobDirectory))
                {
                    CloudBlobDirectory directory = (CloudBlobDirectory)item;
                    Console.WriteLine($"Directory: {directory.Uri}");
                }
            }
            return true;
        }
        public bool CreateBlockBlob(string blockBlobName, string filePath)
        {
            CloudBlobContainer.CreateIfNotExists();
            CloudBlockBlob cloudBlockBlob = CloudBlobContainer.GetBlockBlobReference(blockBlobName);
            using (var fileStream = System.IO.File.OpenRead(filePath))
            {
                cloudBlockBlob.UploadFromStream(fileStream);
                return true;
            }
        }


        public bool ListContainerProperties()
        {
            CloudBlobContainer.FetchAttributes();
            Console.WriteLine($"Container Name {CloudBlobContainer.Name} was last modified on " +
                              $"{CloudBlobContainer.Properties.LastModified}: {CloudBlobContainer.Uri}");

            foreach (var item in CloudBlobContainer.Metadata)
            {
                Console.WriteLine($"Key {item.Key} has Value {item.Value}");
            }
            return true;
        }

        public bool AddMetaData(List> properties)
        {
            foreach (var v in properties)
            {
                CloudBlobContainer.Metadata.Add(v.Key, v.Value);
            }
            CloudBlobContainer.SetMetadata();
            return true;
        }
        public bool ClearMetaDataKey(string Key)
        {
            CloudBlobContainer.Metadata.Remove(Key);
            CloudBlobContainer.SetMetadata();
            return true;
        }

        public bool CopyBlobAsync(string fromBlockBlob, string toBlockBlob)
        {
            CloudBlockBlob fromCloudBlockBlobReference = CloudBlobContainer.GetBlockBlobReference(fromBlockBlob);
            CloudBlockBlob toCloudBlockBlobReference = CloudBlobContainer.GetBlockBlobReference(toBlockBlob);
            toCloudBlockBlobReference.StartCopyAsync(new Uri(fromCloudBlockBlobReference.Uri.ToString()));
            return true;
        }

        internal bool CreateFolderStructure(string fromFilePath,string parentDirName,string childDirName,string targetBlobName)
        {
            CloudBlobDirectory parentDirBlobReference = CloudBlobContainer.GetDirectoryReference(parentDirName);
            CloudBlockBlob cloudBlockBlob  = parentDirBlobReference.GetBlockBlobReference(targetBlobName);
            if(!string.IsNullOrEmpty(childDirName))
            {
                CloudBlobDirectory childDirBlobReference = parentDirBlobReference.GetDirectoryReference(childDirName);
                cloudBlockBlob = childDirBlobReference.GetBlockBlobReference(targetBlobName);
            }
           
            using (var fileStream = System.IO.File.OpenRead(fromFilePath))
            {
                cloudBlockBlob.UploadFromStream(fileStream);
                return true;
            }
        }
    }
}


Code for "Program.cs"


using System;
using System.Collections;
using System.Collections.Generic;

namespace AzureWorkshop
{
    class MainClass
    {


        public static void Main(string[] args)
        {
            var containerName = "brodeoblobcontainer";
            var blobStorageContainer = new BlobStorageContainer(containerName);
            //Delete(blobStorageContainer,containerName);

            Console.ReadLine();
        }

        public static void Delete(BlobStorageContainer blobStorageContainer, string containerName)
        {
            if (blobStorageContainer.Delete())
            {
                Console.WriteLine($"{containerName} deleted sucessfully!!!");
            }

            else
            {
                Console.WriteLine($"{containerName} not deleted it may not already be existing...");
            }
            Console.WriteLine("Done!!!");

        }


        public static void ClearMetaData(BlobStorageContainer blobStorageContainer)
        {
            blobStorageContainer.ClearMetaDataKey("createdby");
            Console.WriteLine("Done!!!");

        }

        public static void CopyBlobAsync(BlobStorageContainer blobStorageContainer)
        {
            blobStorageContainer.CopyBlobAsync("brodeoblockblob1", "brodeoblockblob1Copy");
            Console.WriteLine("Operation Initiated Successfully!!!");

        }


        public static void AddMetaData(BlobStorageContainer blobStorageContainer)
        {
            List> properties = new List>();
            properties.Add(new KeyValuePair<string, string>("CreatedBy", "Byte Rodeo"));
            properties.Add(new KeyValuePair("CreatedOn", System.DateTime.Now.ToString()));
            blobStorageContainer.AddMetaData(properties);
            Console.WriteLine("Done!!!");

        }





        public static void ListContainerProperties(BlobStorageContainer blobStorageContainer)
        {
            blobStorageContainer.ListContainerProperties();
            Console.WriteLine("Done!!!");

        }


        public static void CreateFolderStructure(BlobStorageContainer blobStorageContainer)
        {
            var parentDirName = "brParentDir";
            var childDirName = "brChildDir";
            var filePath = @"/Users/********/Downloads/********.pdf";
            var targetBlobName = @"brBlockBlob1";

            blobStorageContainer.CreateFolderStructure(filePath, parentDirName, childDirName, targetBlobName);
            Console.WriteLine("Operation Completed Successfully!!!");

        }


        public static void ListAllBlobs(BlobStorageContainer blobStorageContainer, string containerName)
        {
            blobStorageContainer.ListAllBlobs(containerName);
            Console.WriteLine("Done!!!");
        }

        public static void CreateBlockBlob(BlobStorageContainer blobStorageContainer)
        {
            var blockBlobName = "brodeoblockblob1";
            var filePath = @"/Users/Parwinder/Downloads/sample1.pdf";
            if (blobStorageContainer.CreateBlockBlob(blockBlobName, filePath))
            {
                Console.WriteLine($"{blockBlobName} created sucessfully!!!");
            }
            else
            {
                Console.WriteLine($"{blockBlobName} may already be existing...");
            }

            Console.WriteLine("Done!!!");

        }


        public static void Create(BlobStorageContainer blobStorageContainer, string containerName)
        {
            if (blobStorageContainer.Create())
            {
                Console.WriteLine($"{containerName} created sucessfully!!!");
            }
            else
            {
                Console.WriteLine($"{containerName} not created it may already be existing...");
            }
            Console.WriteLine("Done!!!");

        }
    }
}


Resources

https://docs.microsoft.com/en-us/azure/storage/blobs/storage-quickstart-blobs-dotnet?tabs=macos

Comments

Popular posts from this blog

Azure - Manage Blob Storage - Part #7 - Add Metadata to an Existing Container using C#

Azure - Manage Blob Storage - Part #5 - Create Folder Structure and upload a file to folder using an Existing Container using C#

Algorithm - Breadth First Search(BFS) - Python(3)