Get all blobs in a container and change the content type.

Posted by Anuraj on Monday, May 13, 2019 Reading time :1 minute

Azure AzureBlob

This post is about getting all the blobs in a container and change the content type. This tip or snippet is quite useful in scenarios where you want to change content type of big number of blobs. This is a tip or snippet more than a blog post. I faced this issue in my current project, where our application used to push images to Azure Blob, but we were not setting the content type, and by default the content type is application/octet-stream. Because of this, when we used to browse the URL, instead of displaying it in the browser, browser used to show a download prompt. In this I am using a dotnet core console app, which will get all the blobs and if the extension of the file is jpg, setting the content type to image/jpg.

Here is the code.

BlobContinuationToken continuationToken = null;
var storageAccount = CloudStorageAccount.Parse("<Connection String>");
var blobClient = storageAccount.CreateCloudBlobClient();
do
{
    var blobs = blobClient.GetContainerReference("img")
        .ListBlobsSegmentedAsync(continuationToken);
    var result = blobs.Result;
    continuationToken = result.ContinuationToken;
    var images = result.Results.ToList();
    for (int i = 0; i < images.Count; i++)
    {
        var image = images[i];
        if (image.GetType() == typeof(CloudBlockBlob)
            && Path.GetExtension(image.Uri.ToString()) == ".jpg")
        {
            var blob = (CloudBlockBlob)image;
            blob.Properties.ContentType = "image/jpeg";
            blob.SetPropertiesAsync();
            Console.WriteLine($"{i}-{image.Uri}");
        }
    }
} while (continuationToken != null);

Right now I am using the NuGet reference of WindowsAzure.Storage. You can do it with Microsoft.Azure.Storage.Blob package as well.

Happy Programming :)

What do you think? I would like to hear your thoughts, suggestions, and questions in the comments section below.


Similar Posts


Did you like this article? Share it with your friends

Facebook Twitter Google+ LinkedIn Reddit StumbleUpon



Translate
Subscribe
BMC logoBuy me a coffee


Copyright © 2019 - Anuraj P. Blog content licensed under the Creative Commons CC BY 2.5 | Unless otherwise stated or granted, code samples licensed under the MIT license. This is a personal blog. The opinions expressed here represent my own and not those of my employer. Hosted with ❤ by GitHub