Upload And Download Files From Blob Storage Using C#

This is the second part of the Introduction to Azure Blob storage. Here we will see how to access the Azure blog storage for uploading and downloading files using C#.

If you do not have a storage account, please read the first part of this article to create an Azure storage account.

You can find the first part here >> Create an Azure Storage account and a storage container for blob storage

Once we have created the Azure storage account and container let’s develop a simple C# console application to upload and download the files to the blob storage programmatically.

First, create a C# console application.

Console app

To access the Azure storage account we need to install the NuGet package WindowsAzure.Storage.

Nuget package manager

I have installed the latest version v9.3.3.

Window Azure storage

After the package has been installed, we need to include the following references in our application.

using Microsoft.Azure;    
using Microsoft.WindowsAzure.Storage;    
using Microsoft.WindowsAzure.Storage.Blob; 

In the main method, I have created 2 methods

  1. Upload_ToBlob(local_file_Path, Azure_container_Name): To upload the file to the Blob storage
  2. Download_FromBlob(filename_with_Extention, Azure_container_Name): To download the file from the Blob storage

Please refer to the code snippet below.

static void Main(string[] args) 
{ 
    AzureBlobSample azureBlob = new AzureBlobSample();    
    azureBlob.upload_ToBlob("D:\\data_d.txt", "mydatacontainer"); 
    azureBlob.download_FromBlob("data_d.txt", "mydatacontainer"); 
    Console.ReadKey(); 
}

Upload files to the Blob storage

The method definition for the Upload_ToBlob() is given below.

Here I am using 2 parameters for the method.

One for the file name and the other for the Azure container name.

public void upload_ToBlob(string fileToUpload, string azure_ContainerName)
{
    Console.WriteLine("Inside upload method");
    string file_extension, filename_withExtension, storageAccount_connectionString;
    Stream file;
    // Copy the storage account connection string from Azure portal
    storageAccount_connectionString = "your Azure storage account connection string here";
    // Reading the file as filestream from local machine
    file = new FileStream(fileToUpload, FileMode.Open);
    CloudStorageAccount mycloudStorageAccount = CloudStorageAccount.Parse(storageAccount_connectionString);
    CloudBlobClient blobClient = mycloudStorageAccount.CreateCloudBlobClient();
    CloudBlobContainer container = blobClient.GetContainerReference(azure_ContainerName);
    // Checking if the container exists or not
    if (container.CreateIfNotExists())
    {
        container.SetPermissionsAsync(new BlobContainerPermissions
        {
            PublicAccess = BlobContainerPublicAccessType.Blob
        });
    }
    // Reading file name and file extension
    file_extension = Path.GetExtension(fileToUpload);
    filename_withExtension = Path.GetFileName(fileToUpload);
    CloudBlockBlob cloudBlockBlob = container.GetBlockBlobReference(filename_withExtension);
    cloudBlockBlob.Properties.ContentType = file_extension;
    cloudBlockBlob.UploadFromStreamAsync(file); // Uploading the file to the blob
    Console.WriteLine("Upload Completed!");
}

In the above method, we copied the storage account connection string from the Azure portal.

Azure can find the connection string by clicking the Access Keys menu in the Settings section.

Please refer to the screenshot below.

Access keys

Copy the connection string and assign it to the storageAccount_connectionString variable in the upload_ToBlob() method.

storageAccount_connectionString = "your Azure storage account connection string";

The below 3 statements are used to create the objects for the Storage Account, Blob client, and Blob container.

CloudStorageAccount mycloudStorageAccount = CloudStorageAccount.Parse(storageAccount_connectionString);
CloudBlobClient blobClient = mycloudStorageAccount.CreateCloudBlobClient();
CloudBlobContainer container = blobClient.GetContainerReference(azure_ContainerName);

The below code snippet checks whether the specified container exists in storage a, account, or not.

If it exists, the application will use the existing container. Otherwise, it will create a container inside the storage account with a specified name.

if (container.CreateIfNotExists())
{
    container.SetPermissionsAsync(new BlobContainerPermissions
    {
        PublicAccess = BlobContainerPublicAccessType.Blob
    });
}

The below statement is used to create a Block blob object using the filthe e name with extension.a

CloudBlockBlob cloudBlockBlob = container.GetBlockBlobReference(filename_withExtension);

cloudBlockBlob.UploadFromStreamAsync(file) statement is used to upload the file to the blob storage.

Download files from the Blob storage

In my implementation, I have used 2 parameters for the download_FromBlob() method.

One is the File Name and the other one is the Azure container name.

The definition for the download_FromBlob() method is given below.

public void download_FromBlob(string filetoDownload, string azure_ContainerName) {
    Console.WriteLine("Inside downloadfromBlob()");
    string storageAccount_connectionString = "Paste you storage account connection string here";
    CloudStorageAccount mycloudStorageAccount = CloudStorageAccount.Parse(storageAccount_connectionString);
    CloudBlobClient blobClient = mycloudStorageAccount.CreateCloudBlobClient();
    CloudBlobContainer container = blobClient.GetContainerReference(azure_ContainerName);
    CloudBlockBlob cloudBlockBlob = container.GetBlockBlobReference(filetoDownload);
    // provide the file download location below
    Stream file = File.OpenWrite(@"E:\Tools\BlobFile\" + filetoDownload);
    cloudBlockBlob.DownloadToStream(file);
    Console.WriteLine("Download completed!");
}

The codes are the same as the upload method.

cloudBlockBlob.DownloadToStream(file) statement is used to download, and add the file from the blob storage.

Since it is a basic application, I haven’t used any validation to check whether the file and the container exist or not.

You can add more logic to make the application more secure and accurate.

Happy Coding


Similar Articles