Today, I will explain how to create Azure Blob Storage and upload and download files from Azure Blob Storage using C#.
Step 1 - Create Azure Blob Storage
Link - Portal.Azure.com.
In the left menu, click on Storage. It will take you to the Microsoft Storage account.
Step 2
Add a new Storage Account by clicking the Add button.
Navigate to the Blob Service section, as shown below.
Next, create a container for the Blob to add files into the container using the Upload button, as shown below.
Navigate to the Storage Account (which you created) -> AccessKey, copy connection string which is used to connect to the Blob from C# code.
Step 3 - Programming part
Add the required reference using NuGet.
- using Microsoft.Azure;
- using Microsoft.WindowsAzure.Storage;
- using Microsoft.WindowsAzure.Storage.Blob;
NuGet Package Manager is,
Install-Package WindowsAzure.Storage -Version 9.3.2
Add the Azure Storage Account Connection String in App.config which I explained in the previous screenshot. Copy the below code and reference the file which is to be uploaded. The code will work like a charm.
- string storageConnection = CloudConfigurationManager.GetSetting("BlobStorageConnectionString");
- CloudStorageAccount cloudStorageAccount = CloudStorageAccount.Parse(storageConnection);
-
-
-
- if (await cloudBlobContainer.CreateIfNotExistsAsync()) {
- await cloudBlobContainer.SetPermissionsAsync(new BlobContainerPermissions {
- PublicAccess = BlobContainerPublicAccessType.Blob
- });
- }
- string imageName = "Test-" + Path.GetExtension(imageToUpload.FileName);
-
- CloudBlockBlob cloudBlockBlob = cloudBlobContainer.GetBlockBlobReference(imageName);
- cloudBlockBlob.Properties.ContentType = imageToUpload.ContentType;
- await cloudBlockBlob.UploadFromStreamAsync(imageToUpload.InputStream);
Step 3.1
Download file from Azure Blob using C#.
- var containerName = "testcontainerherbi";
-
- string storageConnection = CloudConfigurationManager.GetSetting("BlobStorageConnectionString"); CloudStorageAccount cloudStorageAccount = CloudStorageAccount.Parse(storageConnection); CloudBlobClient blobClient = cloudStorageAccount.CreateCloudBlobClient();
-
- CloudBlobContainer cloudBlobContainer = blobClient.GetContainerReference(containerName); CloudBlockBlob blockBlob = cloudBlobContainer.GetBlockBlobReference("uploadedfilename.ext");
-
- MemoryStream memStream = new MemoryStream();
-
- blockBlob.DownloadToStream(memStream);
-
- HttpContext.Current.Response.ContentType = blockBlob.Properties.ContentType.ToString(); HttpContext.Current.Response.AddHeader("Content-Disposition", "Attachment; filename=" + blockBlob.ToString());
-
- HttpContext.Current.Response.AddHeader("Content-Length", blockBlob.Properties.Length.ToString()); HttpContext.Current.Response.BinaryWrite(memStream.ToArray()); HttpContext.Current.Response.Flush(); HttpContext.Current.Response.Close();
Please download the attached file.
I hope it's helpful. Eat-> Code->Sleep->Repeat.