SHEKHAR SHETE
SHEKHAR SHETE

Reputation: 6056

How to read/Download all files from a Azure container/Blob using C#?

I am new bee to Azure Storage. So, please consider text/code in post. I have some files stored on Azure Storage.

Example:

http://my.blob.core.windows.net/2015/4/10/fea1fc9d-d04102015115229.jpg
http://my.blob.core.windows.net/2015/4/10/asdfc9d-d04102015115229.jpg

Now i want to download these files using Container/Blob name to specific folder.

DownloadFiles.aspx:

protected void Callme(string sourceURLPath)
    {
        string thumbDirectoryName = string.Empty;
        string sourcePath = sourceURLPath;
        string targetUrl = string.Empty;

        CloudStorageAccount cloudStorageAccount;
        CloudBlobClient blobClient;
        CloudBlobContainer blobContainer;
        BlobContainerPermissions containerPermissions;
        CloudBlob blob;
        cloudStorageAccount = CloudStorageAccount.Parse("DefaultEndpointsProtocol=http;AccountName=" + ConfigurationManager.AppSettings["AzureStorageAccountName"] + ";AccountKey=" + ConfigurationManager.AppSettings["AzureStorageAccountKey"] + "");
 blobClient = cloudStorageAccount.CreateCloudBlobClient();
  blobContainer = blobClient.GetContainerReference(DateTime.Now.Year.ToString());
  blobContainer.CreateIfNotExist();
 containerPermissions = new BlobContainerPermissions();
  containerPermissions.PublicAccess = BlobContainerPublicAccessType.Blob;
        blobContainer.SetPermissions(containerPermissions);
//need to get files here and download in to specific folder
}

Any suggestions?

Upvotes: 0

Views: 4358

Answers (1)

Gaurav Mantri
Gaurav Mantri

Reputation: 136146

You're almost there :). Here's what you would need to do:

  • First you have to list blobs in the container. To do so, you can use ListBlobs method on your container. When listing blobs, please make sure that you pass prefix as empty string (string.Empty) and useFlatBlobListing as true. This will give a list of blobs in your container.
  • Next you will iterate through the list of blobs, cast each blob as CloudBlockBlob and then call DownloadToFile method on each blob.

A few suggestions regarding your code:

  • Since you're reading files from a blob container thus that container already exists. So no need to try to create that container on each request. Or in other words, get rid of this line from your code:

    blobContainer.CreateIfNotExist();

  • Similarly, you don't need the following lines of code as well because all you're doing is reading the blobs.

    containerPermissions = new BlobContainerPermissions(); containerPermissions.PublicAccess = BlobContainerPublicAccessType.Blob; blobContainer.SetPermissions(containerPermissions);

Upvotes: 4

Related Questions