Saturday, January 21, 2012

How to Rename a blob on Azure

I came across something today that I think it is good to share, blob names are case-sensitive in windows Azure. So I had to write a program to rename all blobs and change them to lower case. here is the code.

using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.WindowsAzure;
using Microsoft.WindowsAzure.StorageClient;

namespace MyBlobRenameApp
    public class Process
        private static void RenameBlobs()
            string blobConName = ConfigHelper.BlobContainerName;

            string dataCenterSettingKey = "DefaultEndpointsProtocol=" + 
                                           ConfigHelper.DefaultEndpointsProtocol +
                                          ";AccountName=" + 
                                          ConfigHelper.AccountName +
                                          ";AccountKey=" + 

            CloudStorageAccount cloudStorageAccount = 

            CloudBlobClient blobClient = cloudStorageAccount.CreateCloudBlobClient();

            CloudBlobContainer container = 
            // Create the container if it does not exist.

            // Set permissions on the container.
            BlobContainerPermissions permissions = new BlobContainerPermissions();

            containerPermissions.PublicAccess = BlobContainerPublicAccessType.Blob;

           //For example we have 2 blobs VSN/b1 and VSN/b2
            var blobs = container.GetDirectoryReference("VSN").ListBlobs();
            foreach (var item in blobs)
                string blobUri = item.Uri.ToString();

                CloudBlob existBlob = container.GetBlobReference(blobUri);
                CloudBlob newBlob = container.GetBlobReference(blobUri.ToLower());



Hopefully this post will be useful to somebody who runs into the same problem.


AndrewK said...

Thanks a lot for example.

Alex said...

I believe this could be simplified slightly.

Instead of getting blob reference by passing in the Uri you can just cast the collection of IListBlogItem to CloudBlob because CloudBlob inherits from IListBlogItem.

foreach (var existBlob in blobs.ToList().Cast<CloudBlob>())
var newBlob = container.GetBlobReference(existBlob.Name.ToLower());

Hope that helps :)

jvongillern said...

In v2 of the api, CopyFromBlob changed to StartCopyFromBlob, so it is possible that the delete will finish before the copy does and you'll end up losing data. It caused me some pain so I wanted to spread the word. Writeup:

Post a Comment