Change Content Type for files in Azure Storage Blob

user2403260 Source

I use only Microsoft Azure Storage and no other Azure products/services. I upload files to my storage blob via ftp type client (GoodSync), and I need to change the content type of all the files based on their file extension after they are already in the Blob. I have looked around and have not found out how to do this without having one of their VPS with PowerShell. What are my options and how do I accomplish this? I really need step by step here.



answered 3 years ago ppolyzos #1

I recently had the same issue so I created a simple utility class in order to "fix" content type based on file's extension. You can read details here

What you need to do is parse each file in your Azure Storage Containers and update ContentType based on a dictionary that defines which MIME type is appropriate for each file extension.

// Connect to your storage account
CloudStorageAccount storageAccount = CloudStorageAccount.Parse(storageConnectionString);

// Load Container with the specified name 
private CloudBlobContainer GetCloudBlobContainer(string name)
    CloudBlobClient cloudBlobClient = _storageAccount.CreateCloudBlobClient();
    return cloudBlobClient.GetContainerReference(name.ToLowerInvariant());
// Parse all files in your container and apply proper ContentType
private void ResetContainer(CloudBlobContainer container)
    if (!container.Exists()) return;

    Trace.WriteLine($"Ready to parse {container.Name} container");

    var blobs = container.ListBlobs().ToList();

    var total = blobs.Count;
    var counter = 1;

    foreach (var blob in blobs)
        if (blob is CloudBlobDirectory) continue;

        var cloudBlob = (CloudBlob)blob;

        var extension = Path.GetExtension(cloudBlob.Uri.AbsoluteUri);

        string contentType;
        _contentTypes.TryGetValue(extension, out contentType);
        if (string.IsNullOrEmpty(contentType)) continue;

        Trace.Write($"{counter++} of {total} : {cloudBlob.Name}");
        if (cloudBlob.Properties.ContentType == contentType)
            Trace.WriteLine($" ({cloudBlob.Properties.ContentType}) (skipped)");

        cloudBlob.Properties.ContentType = contentType;
        Trace.WriteLine($" ({cloudBlob.Properties.ContentType}) (reset)");

_contentTypes is a dictionary that contains the appropriate MIME type for each file extension:

    private readonly Dictionary _contentTypes = new Dictionary()
        {".jpeg", "image/jpeg"},
        {".jpg", "image/jpeg" }

Full list of content types and source code can be found here.

comments powered by Disqus