# 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 (opens new window). If you want to start from this post, then use the code located here (opens new window).

What is User-defined metadata? User-defined metadata (opens new window) 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)
{
    BlobServiceClient storageAccount = new BlobServiceClient(CloudConfigurationManager.GetSetting("StorageConnection"));
    BlobContainerClient container = storageAccount.GetBlobContainerClient("images-backup");
    container.CreateIfNotExists(PublicAccessType.Blob);
    //add method
    SetMetadata(container);
    //add method
    Console.ReadLine();
}

static void SetMetadata(BlobContainerClient container)
{
    //clear metadata
    container.SetMetadata(new Dictionary<string, string>());

    Dictionary<string, string> metadata = new Dictionary<string, string>(2);
    metadata.Add("Owner", "Michael Crump");
    metadata["LastUpdated"] = DateTime.Now.ToString();
    //set metadata
    container.SetMetadata(metadata);
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22

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(BlobContainerClient container)
{
    //retrieve container metadata
    BlobContainerProperties properties = container.GetProperties();
    foreach (var metadata in properties.Metadata)
    {
        Console.WriteLine(string.Format($"{metadata.Key}: {metadata.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: