Downloading file as byte array from AZURE BLOB storage in WCF Service

In this post I will show you how you can download a file from AZURE BLOB storage as byte array.

Contract


using System.Collections.Generic;
using System.IO;
using System.ServiceModel;
using WcfService15testapi.Entities;

namespace WcfService15testapi
{

    [ServiceContract]
    public interface IService1
    {

       [OperationContract]

        byte[] DownLoadFileForBLOB(string ContainerName, string fileName);
    }

}

To download file client will have to provide ContainerName and filename to be downloaded.

Service Implementation

Very first you need to add reference of,

Microsoft.WindowsAzure

Microsoft.WindowsAzure.StorageClient

Second you need to create connection string to fetch file from AZURE BLOB.

Connection String

DefaultEndPoint=https;AccountName=STORAGEACCOUNTNAME;AccountKey=ACCOUNTKEY

So if yours,

Storage Account Name = “Test Account

Storage Account Key = “xxxxxxxxxxxxxxxxxxxxxx/xxxxxxx==” 

Then connection string to AZURE Storage account would be,

DefaultEndPoint=https;AccountName= Test Account;AccountKey= xxxxxxxxxxxxxxxxxxxxxx/xxxxxxx==

Container Name

We are going to downloads file from public container. Let us say public container name is TESTCONTAINER.

Full Service implementation is as below,


using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Security.Cryptography.X509Certificates;
using System.Xml.Linq;
using WcfService15testapi.Entities;
using Microsoft.WindowsAzure;
using Microsoft.WindowsAzure.StorageClient;

namespace WcfService15testapi
{

    public class Service1 : IService1
    {
        public byte[]   DownLoadFileForBLOB (string ContainerName, string fileName)
        {

            CloudStorageAccount cloudStorageAccount = CloudStorageAccount.Parse("DefaultEndpointsProtocol=https;AccountName= Test Account;AccountKey=xxxxxxx==");
            CloudBlobClient cloudBlobClient = cloudStorageAccount.CreateCloudBlobClient();
            CloudBlobContainer cloudBlobContainer = cloudBlobClient.GetContainerReference(ContainerName);
            CloudBlob cloudBlob = cloudBlobContainer.GetBlobReference(fileName);
            byte[] byteData = cloudBlob.DownloadByteArray();
                        return byteData;

        }
    }
}

2 thoughts on “Downloading file as byte array from AZURE BLOB storage in WCF Service

Leave a comment