Move Blob between Containers in Azure

Rajnilari2015
Posted by in Azure category on for Beginner level | Points: 250 | Views : 12818 red flag

Azure Blob storage is a service for storing large amounts of unstructured data.In this article we will look how we can move blob between two containers.


 Download source code for Move Blob between Containers in Azure

Introduction

Azure Blob storage is a service for storing large amounts of unstructured data.In this article we will look how we can move blob between two containers.

Step 1: Create a Source and Destination Blob Container in the Azure Portal

Open the Azure portal(https://portal.azure.com), and then choose Storage Account say Containers

Create a source container say sourcecontainer

Likewise,create a destination container say destinationcontainer

It will appear as

Step 2: Upload a file in the Source Container

We have uploaded a html file into the source container.

Step 3: Moving the blob between the containers programatically

Fire up a console application and add the below Nuget packages

Install-Package WindowsAzure.Storage

Install-Package Microsoft.WindowsAzure.ConfigurationManager

Next write the below function

/// <summary>
/// GetBlobContainerReference
/// Gets a reference to the CloudBlobContainer
/// </summary>
/// <param name="connectionString"></param>
/// <param name="containerName"></param>
/// <returns></returns>
private static CloudBlobContainer GetBlobContainerReference(string connectionString, string containerName)
{
    //Get the Microsoft Azure Storage account
    CloudStorageAccount storageAccount = CloudStorageAccount.Parse(connectionString);

    //Create the Blob service client.
    CloudBlobClient blobclient = storageAccount.CreateCloudBlobClient();

    //Returns a reference to a Microsoft.WindowsAzure.Storage.Blob.CloudBlobContainer object with the specified name.
    CloudBlobContainer blobcontainer = blobclient.GetContainerReference(containerName);  
    
             
    return blobcontainer;
}

The above function will return a reference to the CloudBlobContainer object with the name specified.

/// <summary>
/// MoveBlobBetweenContainers
/// Move a blob from source to destination container
/// </summary>
/// <param name="srcBlob"></param>
/// <param name="destContainer"></param>
private static void MoveBlobBetweenContainers(CloudBlockBlob srcBlob, CloudBlobContainer destContainer)
{
    CloudBlockBlob destBlob;           

    //Copy source blob to destination container
    using (MemoryStream memoryStream = new MemoryStream())
    {                
        srcBlob.DownloadToStream(memoryStream);

        //put the time stamp
        var newBlobName = srcBlob.Name.Split('.')[0] + "_" + DateTime.Now.ToString("ddMMyyyy", CultureInfo.InvariantCulture) + "." + srcBlob.Name.Split('.')[1];
       
        destBlob = destContainer.GetBlockBlobReference(newBlobName);

        //copy source blob content to destination blob
        destBlob.StartCopy(srcBlob);              
       
    }
    //remove source blob after copy is done.
    srcBlob.Delete();
}

This function reads the source blob's content and copies to the destination blob. Kindly note that, the destination blob's name is timestamped. After the operation is over, the program deletes the source blob.

Now inside the main function, let us write the below code

static void Main(string[] args)
{           
    string connectionString = CloudConfigurationManager.GetSetting("StorageConnectionString"); //blob connection string
    string sourceContainerName = ConfigurationManager.AppSettings["sourcecontainerName"]; //source container name
    string destinationContainerName = ConfigurationManager.AppSettings["destinationcontainerName"]; //destination container name
    string sourceBlobFileName = "source.html"; //source blob name

    //Gets a reference to the CloudBlobContainer
    var sourceBlobContainerReference = GetBlobContainerReference(connectionString, sourceContainerName);
    var destinationBlobContainerReference = GetBlobContainerReference(connectionString, destinationContainerName);

    var sourceBlob = sourceBlobContainerReference.GetBlockBlobReference(sourceBlobFileName);

    MoveBlobBetweenContainers(sourceBlob, destinationBlobContainerReference); 
           
}

The program invokes the MoveBlobBetweenContainers function to move the blob. To get the Blob Connection string, go to Access key section, and get the Connection String

The app.config file looks as under

  <appSettings>    
    <add key="StorageConnectionString" value="DefaultEndpointsProtocol=https;AccountName=testaccount;AccountKey=CRd****==;EndpointSuffix=core.windows.net" />   
    <add key="sourcecontainerName" value="sourcecontainer" />
    <add key="destinationcontainerName" value="destinationcontainer" />
  </appSettings>

The complete program is as under

using Microsoft.Azure;
using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Blob;
using System;
using System.Configuration;
using System.Globalization;
using System.IO;

namespace UploadFilesToBlob
{
    class Program
    {
        static void Main(string[] args)
        {           
            string connectionString = CloudConfigurationManager.GetSetting("StorageConnectionString"); //blob connection string
            string sourceContainerName = ConfigurationManager.AppSettings["sourcecontainerName"]; //source blob container name
            string destinationContainerName = ConfigurationManager.AppSettings["destinationcontainerName"]; //destination blob container name
            string sourceBlobFileName = "source.html"; //source blob name            

            //Gets a reference to the CloudBlobContainer
            var sourceBlobContainerReference = GetBlobContainerReference(connectionString, sourceContainerName);
            var destinationBlobContainerReference = GetBlobContainerReference(connectionString, destinationContainerName);

            var sourceBlob = sourceBlobContainerReference.GetBlockBlobReference(sourceBlobFileName);           

           MoveBlobBetweenContainers(sourceBlob, destinationBlobContainerReference); 
            
        }

        /// <summary>
        /// MoveBlobBetweenContainers
        /// Move a blob from source to destination container
        /// </summary>
        /// <param name="srcBlob"></param>
        /// <param name="destContainer"></param>
        private static void MoveBlobBetweenContainers(CloudBlockBlob srcBlob, CloudBlobContainer destContainer)
        {
            CloudBlockBlob destBlob;           

            //Copy source blob to destination container
            using (MemoryStream memoryStream = new MemoryStream())
            {                
                srcBlob.DownloadToStream(memoryStream);

                //put the time stamp
                var newBlobName = srcBlob.Name.Split('.')[0] + "_" + DateTime.Now.ToString("ddMMyyyy", CultureInfo.InvariantCulture) + "." + srcBlob.Name.Split('.')[1];
               
                destBlob = destContainer.GetBlockBlobReference(newBlobName);

                //copy source blob content to destination blob
                destBlob.StartCopy(srcBlob);              
               
            }
            //remove source blob after copy is done.
            srcBlob.Delete();
        }



        /// <summary>
        /// GetBlobContainerReference
        /// Gets a reference to the CloudBlobContainer
        /// </summary>
        /// <param name="connectionString"></param>
        /// <param name="containerName"></param>
        /// <returns></returns>
        private static CloudBlobContainer GetBlobContainerReference(string connectionString, string containerName)
        {
            //Get the Microsoft Azure Storage account
            CloudStorageAccount storageAccount = CloudStorageAccount.Parse(connectionString);

            //Create the Blob service client.
            CloudBlobClient blobclient = storageAccount.CreateCloudBlobClient();

            //Returns a reference to a Microsoft.WindowsAzure.Storage.Blob.CloudBlobContainer object with the specified name.
            CloudBlobContainer blobcontainer = blobclient.GetContainerReference(containerName);  
            
                     
            return blobcontainer;
        }       
    }
}

Now let us run the program. The file has been copied to destination container with timestamped.

And as expected, the blob(source.html) from the source container is deleted.

Conclusion

In this article we looked into how we can move blob between two containers. Hope this will be helpful. Thanks for reading. Zipped file attached.

Page copy protected against web site content infringement by Copyscape

About the Author

Rajnilari2015
Full Name: Niladri Biswas (RNA Team)
Member Level: Platinum
Member Status: Member,Microsoft_MVP,MVP
Member Since: 3/17/2015 2:41:06 AM
Country: India
-- Thanks & Regards, RNA Team


Login to vote for this post.

Comments or Responses

Login to post response

Comment using Facebook(Author doesn't get notification)