Azure Blob Uploads

Earlier today I was talking with Cory Fowler about an issue he was having with an Azure blob upload.  Actually, he offered to help with one of my problems first before he asked me for my thoughts – he’s a real community guy.  Alas I wasn’t able to help him with his problem, but it got me thinking about how to handle basic Blob uploads. 

On the CommunityFTW project I had worked on a few months back I used Azure as the back end for media storage.  The basis was simple: upload media stuffs to a container of my choice.  The end result was this class:

    public sealed class BlobUploadManager
        private static CloudBlobClient blobStorage;

        private static bool s_createdContainer = false;
        private static object s_blobLock = new Object();
        private string theContainer = "";

        public BlobUploadManager(string containerName)
            if (string.IsNullOrEmpty(containerName))
                throw new ArgumentNullException("containerName");


        public CloudBlobClient BlobClient { get; set; }

        public string CreateUploadContainer()
            BlobContainerPermissions perm = new BlobContainerPermissions();
            var blobContainer = blobStorage.GetContainerReference(theContainer);
            perm.PublicAccess = BlobContainerPublicAccessType.Container;

            var sas = blobContainer.GetSharedAccessSignature(new SharedAccessPolicy()
                Permissions = SharedAccessPermissions.Write,
                SharedAccessExpiryTime = DateTime.UtcNow + TimeSpan.FromMinutes(60)

            return new UriBuilder(blobContainer.Uri) { Query = sas.TrimStart('?') }.Uri.AbsoluteUri;

        private void CreateOnceContainer(string containerName)
            this.theContainer = containerName;

            if (s_createdContainer)

            lock (s_blobLock)
                var storageAccount = new CloudStorageAccount(
                                         new StorageCredentialsAccountAndKey(

                blobStorage = storageAccount.CreateCloudBlobClient();
                CloudBlobContainer container = blobStorage.GetContainerReference(containerName);

                    new BlobContainerPermissions()
                        PublicAccess = BlobContainerPublicAccessType.Container

                s_createdContainer = true;

        public string UploadBlob(Stream blobStream, string blobName)
            if (blobStream == null)
                throw new ArgumentNullException("blobStream");

            if (string.IsNullOrEmpty(blobName))
                throw new ArgumentNullException("blobName");


            return blobName.ToLowerInvariant();

With any luck with might help someone trying to jump into Azure.