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:
- Connection Strings of a storage account
- Set up a C# project for accessing the storage account
- Upload a file into blob storage using C#
- Download a file using C# from a blob storage
- Delete a blob using C#
- 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.
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.
- using Microsoft.WindowsAzure.Storage;
- using Microsoft.WindowsAzure.Storage.Blob;
-
- private static string ConnectionSting
- {
- get
- {
- return "your connection string";
- }
- }
-
- public static bool Upload()
- {
- try
- {
-
- var containerName = "your container name";
-
-
- CloudStorageAccount storageAccount = CloudStorageAccount.Parse(ConnectionSting);
-
-
- CloudBlobClient client = storageAccount.CreateCloudBlobClient();
-
-
- CloudBlobContainer container = client.GetContainerReference(containerName);
-
-
- var isCreated = container.CreateIfNotExists();
-
-
- container.SetPermissionsAsync(new BlobContainerPermissions
- { PublicAccess = BlobContainerPublicAccessType.Blob });
-
-
- using (FileStream fileStream = File.Open(@"C:\d\log.txt", FileMode.Open))
- {
-
- using (MemoryStream memoryStream = new MemoryStream())
- {
-
- memoryStream.Position = 0;
-
-
- fileStream.CopyTo(memoryStream);
-
- var fileName = "Test-log.txt";
-
-
- CloudBlockBlob blob = container.GetBlockBlobReference(fileName);
-
-
- string mimeType = "application/unknown";
- string ext = (fileName.Contains(".")) ?
- System.IO.Path.GetExtension(fileName).ToLower() : "." + fileName;
- Microsoft.Win32.RegistryKey regKey =
- Microsoft.Win32.Registry.ClassesRoot.OpenSubKey(ext);
- if (regKey != null && regKey.GetValue("Content Type") != null)
- mimeType = regKey.GetValue("Content Type").ToString();
-
-
-
-
- memoryStream.ToArray();
- memoryStream.Seek(0, SeekOrigin.Begin);
-
-
- blob.Properties.ContentType = mimeType;
-
-
- blob.UploadFromStream(memoryStream);
- }
- }
-
- return true;
- }
- catch (Exception ex)
- {
- throw;
- }
- }
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.
- public static MemoryStream Download()
- {
- var containerName = "your container name";
- var blobName = "blob name that you have set";
-
- CloudStorageAccount storageAccount = CloudStorageAccount.Parse(ConnectionSting);
-
-
- CloudBlobClient client = storageAccount.CreateCloudBlobClient();
-
-
- CloudBlobContainer container = client.GetContainerReference(containerName);
-
-
- CloudBlockBlob blockBlob = container.GetBlockBlobReference(blobName);
-
-
- var allBlobs = container.ListBlobs();
-
-
- MemoryStream memStream = new MemoryStream();
- blockBlob.DownloadToStream(memStream);
- return memStream;
- }
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.
- public static bool DeleteBlob()
- {
- var containerName = "your container name";
- var blobName = "blob name that you have set";
-
- CloudStorageAccount storageAccount = CloudStorageAccount.Parse(ConnectionSting);
-
-
- CloudBlobClient client = storageAccount.CreateCloudBlobClient();
-
-
- CloudBlobContainer container = client.GetContainerReference(containerName);
-
-
- CloudBlockBlob blockBlob = container.GetBlockBlobReference(blobName);
-
-
- return blockBlob.DeleteIfExists()
- }
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,
- public static bool DeleteContainer()
- {
- var containerName = "your container name";
- var blobName = "blob name that you have set";
-
- CloudStorageAccount storageAccount = CloudStorageAccount.Parse(ConnectionSting);
-
-
- CloudBlobClient client = storageAccount.CreateCloudBlobClient();
-
-
- CloudBlobContainer container = client.GetContainerReference(containerName);
-
-
- container.Delete();
- }