Azure Tips and Tricks Part 80 - Adding Metadata to a file inside Azure Storage Blob Container

2 minute read

Azure Developer Guide Book 2nd Edition available now! This free eBook is available now at aka.ms/azuredevebook.

Intro

Most folks aren’t aware of how powerful the Azure platform really is. As I’ve been presenting topics on Azure, I’ve had many people say, “How did you do that?” So I’ll be documenting my tips and tricks for Azure in these posts.

The Complete List of Azure Tips and Tricks

Available Now!

Adding Metadata to a file inside Azure Storage Blob Container

We’ve reviewed the following options with Azure Storage so far:

Today, we are going to look at setting user-defined metadata to a file inside an Azure Storage Blob Container via C#. Go ahead and open the Azure Portal and open the C# app that we worked with earlier. If you want to start from this post, then use the code located here.

What is User-defined metadata? User-defined metadata is metadata that you specify on a given resource in the form of a name-value pair. You can use metadata to store additional values with a storage resource. These additional metadata values are for your own purposes only, and do not affect how the resource behaves.(courtesy of docs)

If you look below, you will notice that there is a way to do this inside the portal.

You’ll notice this is key-value pairs.

We can also do this with code by adding as shown below.

static void Main(string[] args)
{
var storageAccount = CloudStorageAccount.Parse(CloudConfigurationManager.GetSetting("StorageConnection"));
var myClient = storageAccount.CreateCloudBlobClient();
var container = myClient.GetContainerReference("images-backup");
//add method
SetMetadata(container);
//add method
Console.ReadLine();
}

static void SetMetadata(CloudBlobContainer container)
{
    // Add some metadata to the container.
    container.Metadata.Clear();
    container.Metadata.Add("Owner", "Michael Crump");
    container.Metadata["LastUpdated"] = DateTime.Now.ToString();
    container.SetMetadata();
}

This method clears the metadata and add the key-value pair that we talked about earlier.

We can also write a GetMetadata method to retrieve metadata from our container.

static void GetMetadata(CloudBlobContainer container)
{
    container.FetchAttributes();
    foreach (var item in container.Metadata)
    {
        Console.WriteLine(
        string.Format("{0}: {1}", item.Key, item.Value));
    }
}

If we run the application and look at our console output, then we’ll see the following:

Success!

Want more Azure Tips and Tricks?

If you’d like to learn more Azure Tips and Tricks, then follow me on twitter or stay tuned to this blog! I’d also love to hear your tips and tricks for working in Azure, just leave a comment below.

Leave a Comment