Click here to Skip to main content
14,774,612 members
Articles » Desktop Development » Files and Folders » Memory Mapped Files
Article
Posted 6 Jan 2019

Stats

9.1K views
146 downloads
4 bookmarked

Azure Storage Account Part 2: Upload Files in Blob Storage using C#

Rate me:
Please Sign up or sign in to vote.
4.33/5 (2 votes)
6 Jan 2019CPOL
How to upload files in blob storage using C#

Part 1https://www.codeproject.com/Articles/1273552/Azure-Storage-Account-Part-1-What-is-Blob

Part 2https://www.codeproject.com/Articles/1273613/Azure-Storage-Account-Part-2-Upload-Files-in-Blob

Azure Blob logo

In the last post, Azure Storage Account Part 1: What is blob?, of this series, we have seen what is Azure Storage Account and how to manage your files in a 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 up:

  1. Connection Strings of a storage account
  2. Set up C# project for accessing storage account
  3. Upload a file into a 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!

1. Connection Strings of a Storage Account

In the last module, we have covered up the keys and connection strings of an Azure storage account. We will use those connection strings in our application.

Before that, let’s go though 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.

access keys

Copy one of the connection strings, we are going to use it in our application.

2. Set Up 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, couple of references will be added in your solutions:

  • Microsoft.WindowsAzure.KeyVault.Core
  • Microsoft.Windows.Azure.Storage
  • Newtonsoft.Json

Now your application is ready to access the files of Azure storage account.

Please note onwards 9.4.0 library has been split into multiple parts like Microsoft.Azure.Storage.Blob, Microsoft.Azure.Storage.File, Microsoft.Azure.Storage.Queue & Microsoft.Azure.Storage.Common.

3. Upload a File Into a Blob Storage Using C#

First, set the connection string in your application. Set it in Web.Config under 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
	{
		// set your container name
		var containerName = "your container name";
		
		// create object of storage account
		CloudStorageAccount storageAccount = CloudStorageAccount.Parse(ConnectionSting);
		
		// create client of storage account
		CloudBlobClient client = storageAccount.CreateCloudBlobClient();
		
		// create the reference of your storage account
		CloudBlobContainer container = client.GetContainerReference(containerName);
		
		// check if the container exists or not in your account
		var isCreated = container.CreateIfNotExists();
		
		// set the permission to blob type
		container.SetPermissionsAsync(new BlobContainerPermissions 
                   { PublicAccess = BlobContainerPublicAccessType.Blob });

		// read the file to be uploaded
		using (FileStream fileStream = File.Open(@"C:\d\log.txt", FileMode.Open))
		{
			// create the memory steam which will be uploaded
			using (MemoryStream memoryStream = new MemoryStream())
			{
				// set the memory stream position to starting
				memoryStream.Position = 0;
				
				// copy file content to memory stream
				fileStream.CopyTo(memoryStream);

				var fileName  = "Test-log.txt";
				// create the object of blob which will be created
				// Test-log.txt is the name of the blob, pass your desired name
				CloudBlockBlob blob = container.GetBlockBlobReference(fileName);

				// get the mime type of the file
				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();

				// set the memory stream position to zero again
				// this is one of the important stage, If you miss this step, 
				// your blob will be created but size will be 0 byte
				memoryStream.ToArray();
				memoryStream.Seek(0, SeekOrigin.Begin);

				// set the mime type
				blob.Properties.ContentType = mimeType;
				
				// upload the stream to blob
				blob.UploadFromStream(memoryStream);
			}
		}
		
		return true;
	}
	catch (Exception ex)
	{
		throw;
	}
}

Now go to your Azure portal and refresh the blob blade, and you will find your file over there.

4. Download a File Using C# From a Blob Storage

Now after uploading the file, it is time to get the file back as 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";
	// create object of your storage account
	CloudStorageAccount storageAccount = CloudStorageAccount.Parse(ConnectionSting);
	
	// create the client of your storage account
	CloudBlobClient client = storageAccount.CreateCloudBlobClient();
	
	// create reference of container
	CloudBlobContainer container = client.GetContainerReference(containerName);

	// get a particular blob within that container
	CloudBlockBlob blockBlob = container.GetBlockBlobReference(blobName);

	// get list of all blobs in the container
	var allBlobs = container.ListBlobs();

	// convert the blob to memorystream
	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.

5. Delete a Blob Using C#

To delete a blob, 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";
	// create object of your storage account
	CloudStorageAccount storageAccount = CloudStorageAccount.Parse(ConnectionSting);
	
	// create the client of your storage account
	CloudBlobClient client = storageAccount.CreateCloudBlobClient();
	
	// create reference of container
	CloudBlobContainer container = client.GetContainerReference(containerName);

	// get a particular blob within that container
	CloudBlockBlob blockBlob = container.GetBlockBlobReference(blobName);
	
	// delete the blob and return bool
	return blockBlob.DeleteIfExists()
}

To delete all files of a container, you need to loop through all blobs of a container and delete individually.

6. 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";
	// create object of your storage account
	CloudStorageAccount storageAccount = CloudStorageAccount.Parse(ConnectionSting);
	
	// create the client of your storage account
	CloudBlobClient client = storageAccount.CreateCloudBlobClient();
	
	// create reference of container
	CloudBlobContainer container = client.GetContainerReference(containerName);
	
	// delete container
	container.Delete();
}

Parts

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Arkadeep De
Software Developer PwC
India India
I am a Software developer having an experience of 5 years in application development. To get me you can mail me at arkadeepde@gmail.com or you can visit my blog at ASP With Arka

Comments and Discussions

 
PraiseNice one Pin
Member 1411619212-Jan-19 8:14
MemberMember 1411619212-Jan-19 8:14 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.