Azure blob and containers allow you to set your own custom metadata. You can do the same either via a portal or through the C# application.
In this article, we will see how to do it using both methods.
Step 1
For containers, right-click the container and click on Edit Metadata which will open a window to add key-value pairs. Add your custom key-value pairs and click on Save.
Step 2
For Blobs, double-click on the blob or right-click on Blob properties, scroll down, and you can see a provision for adding key-value pairs; once added, click on Save to save the metadata.
Step 3
Add the following method to your class and call the method inside your main function to set the Metadata for the container. Here, we are creating static method called SetMetaData which will take in a CloudBlobContainer object through container reference. First, we are clearing out any existing key-value pairs with Metadata.Clear(), and in this code sample, we’re going to add a key-value pair, the owner as Mohammed Ramees and Updated as Current system time.
- static void SetMetaData(CloudBlobContainer container) {
- container.Metadata.Clear();
- container.Metadata.Add("Owner", "Mohammed Ramees");
- container.Metadata["LastUpdated"] = DateTime.Now.ToString();
- container.SetMetadata();
- }
Step 4
To list the metadata within the application, add the following method to the class and call the same in the main method after the call for SetMetaData. This method is accepting a CloudBlobContainer object, with which we call the FetchAtttributes method to kind of load those key-value pairs into this object, and then looping over them and get the information out.
- static void GetMetaData(CloudBlobContainer container) {
- container.FetchAttributes();
- Console.WriteLine("Container MetaData: \n");
- foreach(var item in container.Metadata) {
- Console.WriteLine(string.Format("{0}: {1}", item.Key, item.Value));
- }
- }
The complete main method code should look like this.
- {
- CloudStorageAccount storageAccount = CloudStorageAccount.Parse(CloudConfigurationManager.GetSetting("StorageConnection"));
- CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
- CloudBlobContainer container = blobClient.GetContainerReference("images");
- container.CreateIfNotExists(BlobContainerPublicAccessType.Blob);
- SetMetaData(container);
- GetMetaData(container);
- Console.ReadKey();
- }
- static void GetMetaData(CloudBlobContainer container) {
- container.FetchAttributes();
- Console.WriteLine("Container MetaData: \n");
- foreach(var item in container.Metadata) {
- Console.WriteLine(string.Format("{0}: {1}", item.Key, item.Value));
- }
- }
- static void SetMetaData(CloudBlobContainer container) {
- container.Metadata.Clear();
- container.Metadata.Add("Owner", "Mi");
- container.Metadata["LastUpdated"] = DateTime.Now.ToString();
- container.SetMetadata();
- }
Step 5
Run the application and you can get the new metadata listed that we added.