TIP

💡 Learn more : Azure storage account overview.

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();
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19

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));
    }
}
1
2
3
4
5
6
7
8
9

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