Azure Storage Account - Part Two - Upload Files In Blob Storage Using C#

In this article, you will learn how to upload files in blob storage using c#.

In the previous post, Azure Storage Account Part 1: What is blob, we have seen what Azure Storage Account is and how to manage your files in blob storage, how to upload and access the files through Azure portal. Here, in this module, we will check how to manage your files (upload, download, delete, copy) in your blobs in an Azure Storage Account.
 
We will cover:
  1. Connection Strings of a storage account
  2. Set up a C# project for accessing the storage account
  3. Upload a file into blob storage using C#
  4. Download a file using C# from a blob storage
  5. Delete a blob using C#
  6. Delete a container using C#
Let’s start!
 

Connection Strings of a Storage Account

 
In the last module, we have covered the keys and connection strings of an Azure storage account. We will use those connection strings in our application.
 
Before that, let’s go through how we can get the connection strings of a storage account. Go to Storage Account from your Azure portal. Choose the storage account from the list of your accounts. And then go to “Access keys” section. Here, you will get your keys & connection strings.
 
Azure Storage Account - Upload Files In Blob Storage Using C#
 
Copy one of the connection strings. We are going to use it in our application.
 

Setup C# Project for Accessing Storage Account

 
Now, create a C# console application (you can create your choice of project types, web or Windows).
 
Next, you have to install WindowsAzure.Storage package from NuGet Package Manager (NPM). Open your NPM Console (NPM) from Tools -> NuGet Package Manager -> Package Manager Console.
 
Now, install WindowsAzure.Storage by running the following command.
 
PM> Install-Package WindowsAzure.Storage -Version 9.3.3
 
After this, a couple of references will be added to your solution.
  • Microsoft.WindowsAzure.KeyVault.Core
  • Microsoft.Windows.Azure.Storage
  • Newtonsoft.Json
Now, your application is ready to access the files of the Azure Storage account.
 
Please note that onwards from 9.4.0, the library has been split into multiple parts like Microsoft.Azure.Storage.Blob, Microsoft.Azure.Storage.File, Microsoft.Azure.Storage.Queue, & Microsoft.Azure.Storage.Common.
 

Upload a File Into a Blob Storage Using C#

 
First, set the connection string in your application. Set it on Web.Config under the appSettings section.
 
Follow the below code snippet to upload a file to blob storage.
  1. using Microsoft.WindowsAzure.Storage;  
  2. using Microsoft.WindowsAzure.Storage.Blob;  
  3.   
  4. private static string ConnectionSting  
  5. {  
  6.     get  
  7.     {  
  8.         return "your connection string";  
  9.     }  
  10. }  
  11.   
  12. public static bool Upload()  
  13. {  
  14.     try  
  15.     {  
  16.         // set your container name  
  17.         var containerName = "your container name";  
  18.           
  19.         // create object of storage account  
  20.         CloudStorageAccount storageAccount = CloudStorageAccount.Parse(ConnectionSting);  
  21.           
  22.         // create client of storage account  
  23.         CloudBlobClient client = storageAccount.CreateCloudBlobClient();  
  24.           
  25.         // create the reference of your storage account  
  26.         CloudBlobContainer container = client.GetContainerReference(containerName);  
  27.           
  28.         // check if the container exists or not in your account  
  29.         var isCreated = container.CreateIfNotExists();  
  30.           
  31.         // set the permission to blob type  
  32.         container.SetPermissionsAsync(new BlobContainerPermissions   
  33.                    { PublicAccess = BlobContainerPublicAccessType.Blob });  
  34.   
  35.         // read the file to be uploaded  
  36.         using (FileStream fileStream = File.Open(@"C:\d\log.txt", FileMode.Open))  
  37.         {  
  38.             // create the memory steam which will be uploaded  
  39.             using (MemoryStream memoryStream = new MemoryStream())  
  40.             {  
  41.                 // set the memory stream position to starting  
  42.                 memoryStream.Position = 0;  
  43.                   
  44.                 // copy file content to memory stream  
  45.                 fileStream.CopyTo(memoryStream);  
  46.   
  47.                 var fileName  = "Test-log.txt";  
  48.                 // create the object of blob which will be created  
  49.                 // Test-log.txt is the name of the blob, pass your desired name  
  50.                 CloudBlockBlob blob = container.GetBlockBlobReference(fileName);  
  51.   
  52.                 // get the mime type of the file  
  53.                 string mimeType = "application/unknown";  
  54.                 string ext = (fileName.Contains(".")) ?   
  55.                             System.IO.Path.GetExtension(fileName).ToLower() : "." + fileName;  
  56.                 Microsoft.Win32.RegistryKey regKey =   
  57.                             Microsoft.Win32.Registry.ClassesRoot.OpenSubKey(ext);  
  58.                 if (regKey != null && regKey.GetValue("Content Type") != null)   
  59.                             mimeType = regKey.GetValue("Content Type").ToString();  
  60.   
  61.                 // set the memory stream position to zero again  
  62.                 // this is one of the important stage, If you miss this step,   
  63.                 // your blob will be created but size will be 0 byte  
  64.                 memoryStream.ToArray();  
  65.                 memoryStream.Seek(0, SeekOrigin.Begin);  
  66.   
  67.                 // set the mime type  
  68.                 blob.Properties.ContentType = mimeType;  
  69.                   
  70.                 // upload the stream to blob  
  71.                 blob.UploadFromStream(memoryStream);  
  72.             }  
  73.         }  
  74.           
  75.         return true;  
  76.     }  
  77.     catch (Exception ex)  
  78.     {  
  79.         throw;  
  80.     }  
  81. }  
Now, go to your Azure portal and refresh the blob blade. You will find your file over there.
 

Download a File Using C# From a Blob Storage

 
Now, after uploading the file, it is time to get the file back as a stream.
 
To do so, follow the below code snippet.
  1. public static MemoryStream Download()  
  2. {  
  3.     var containerName  = "your container name";  
  4.     var blobName = "blob name that you have set";  
  5.     // create object of your storage account  
  6.     CloudStorageAccount storageAccount = CloudStorageAccount.Parse(ConnectionSting);  
  7.       
  8.     // create the client of your storage account  
  9.     CloudBlobClient client = storageAccount.CreateCloudBlobClient();  
  10.       
  11.     // create reference of container  
  12.     CloudBlobContainer container = client.GetContainerReference(containerName);  
  13.   
  14.     // get a particular blob within that container  
  15.     CloudBlockBlob blockBlob = container.GetBlockBlobReference(blobName);  
  16.   
  17.     // get list of all blobs in the container  
  18.     var allBlobs = container.ListBlobs();  
  19.   
  20.     // convert the blob to memorystream  
  21.     MemoryStream memStream = new MemoryStream();  
  22.     blockBlob.DownloadToStream(memStream);  
  23.     return memStream;  
  24. }  
Now, you can create a file from the memory stream or you can pass the stream from a web API.
 

Delete a Blob Using C#

 
To delete a blob, the process is more or less the same. Create the instance of storage account and container. And then, check if the blob is present or not. If present, then delete the same. Microsoft has an inbuilt function to delete the blob. CloudBlockBlob.DeleteIfExists.
  1. public static bool DeleteBlob()  
  2. {  
  3.     var containerName  = "your container name";  
  4.     var blobName = "blob name that you have set";  
  5.     // create object of your storage account  
  6.     CloudStorageAccount storageAccount = CloudStorageAccount.Parse(ConnectionSting);  
  7.       
  8.     // create the client of your storage account  
  9.     CloudBlobClient client = storageAccount.CreateCloudBlobClient();  
  10.       
  11.     // create reference of container  
  12.     CloudBlobContainer container = client.GetContainerReference(containerName);  
  13.   
  14.     // get a particular blob within that container  
  15.     CloudBlockBlob blockBlob = container.GetBlockBlobReference(blobName);  
  16.       
  17.     // delete the blob and return bool  
  18.     return blockBlob.DeleteIfExists()  
  19. }  
To delete all files of a container, you need to loop through all blobs of a container and delete individually.
 

Delete a Container Using C#

 
To delete a whole container, follow the below code snippet. Use CloudBlobContainer.Delete (AccessCondition, BlobRequestOptions, OperationContext) method to delete the container,
  1. public static bool DeleteContainer()  
  2. {  
  3.     var containerName  = "your container name";  
  4.     var blobName = "blob name that you have set";  
  5.     // create object of your storage account  
  6.     CloudStorageAccount storageAccount = CloudStorageAccount.Parse(ConnectionSting);  
  7.       
  8.     // create the client of your storage account  
  9.     CloudBlobClient client = storageAccount.CreateCloudBlobClient();  
  10.       
  11.     // create reference of container  
  12.     CloudBlobContainer container = client.GetContainerReference(containerName);  
  13.       
  14.     // delete container  
  15.     container.Delete();  
  16. }