Azure BlobStorageHelper – Blob create and upload

Code beautifier: http://hilite.me/

Code: 

namespace Helpers
{
    public sealed class BlobStorageHelper : StorageHelper
    {
        private readonly CloudBlobClient _blobClient;
        public string _containerName { get; set; }

        public BlobStorageHelper() : base()
        {
            _blobClient = base.StorageAccount.CreateCloudBlobClient();
            _containerName = ConfigurationManager.AppSettings["StorageContainerName"];
        }


        public Uri CreateBlob(Stream inputStream, string blobName)
        {
            CloudBlobContainer container = _blobClient.GetContainerReference(_containerName);
            container.CreateIfNotExists();

            ICloudBlob blob = container.GetBlockBlobReference(blobName);
            blob.UploadFromStream(inputStream);

            return blob.Uri;
        }

        public Uri CreateBlob(byte[] byteArray, string blobName)
        {
            CloudBlobContainer container = _blobClient.GetContainerReference(_containerName);
            container.CreateIfNotExists();

            ICloudBlob blob = container.GetBlockBlobReference(blobName);
            blob.UploadFromByteArray(byteArray, 0, byteArray.Length);

            return blob.Uri;
        }

        public string GetBlobFileDownloadPath(string blobPath)
        {
            string blobName = blobPath.Substring(blobPath.IndexOf("/" + _containerName + "/")).Replace("/" + _containerName + "/", "");

            CloudBlobContainer container = _blobClient.GetContainerReference(_containerName);
            container.CreateIfNotExists();

            ICloudBlob cloudBlob = container.GetBlobReferenceFromServer(blobName);

            var sasConstraints = new SharedAccessBlobPolicy();
            sasConstraints.SharedAccessExpiryTime = DateTime.UtcNow.AddMinutes(5);
            sasConstraints.Permissions = SharedAccessBlobPermissions.Read;

            var sasBlobToken = cloudBlob.GetSharedAccessSignature(sasConstraints);

            return blobPath + sasBlobToken;
        }

        public void DeleteBlob(string blobPath)
        {
            CloudBlobContainer container = _blobClient.GetContainerReference(_containerName);
            container.CreateIfNotExists();

            CloudBlob cloudBlob = container.GetBlockBlobReference(blobPath);

            cloudBlob.DeleteIfExists();
        }
    }
}

 

Leave a Reply

Your email address will not be published. Required fields are marked *