Question

For a few hours I've been trying to set some metadata on the blob I create using the Azure SDK. I upload the data asynchronously using BeginUploadFromStream() and everything works smoothly. I can access the blob using its URI when the upload has completed, so it is created successfully, however any metadata I set is not persisted.

I set the metadata after calling EndUploadFromStream().

I've tried setting the metadata the three ways I can find through the documentation:

// First attempt
myBlob.Metadata["foo"] = "bar";

// Second attempt
myBlob.Metadata.Add("foo", "bar");

//Third attempt
var metadata = new NameValueCollection();
metadata["foo"] = "bar";
blob.Metadata.Add(metadata);

After setting the metadata i call myBlob.SetMetadata() to save the metadata to Azure, as specified by the documentation, but it does not stick. The call doesn't trow any exceptions, but when I get a new reference to my blob, it doesn't have any metadata.

I've tried saving the metadata asynchronously as well using BeginSetMetadata() and EndSetMetadata() but with similar result.

I start to think I'm missing something really trivial here, but after staring at it for five hours, I still cannot understand where I go wrong?

Was it helpful?

Solution

SetMetadata should work as expected. But simply getting a reference to the blob isn't sufficient to read the metadata.

After getting the blob reference, you need to call the FetchAttributes method on that CloudBlob. This will load all properties and metadata, and only then will you be able to access the metadata you set previously:

// Get a reference to a blob.
CloudBlob blob = blobClient.GetBlobReference("mycontainer/myblob.txt");

// Populate the blob's attributes.
blob.FetchAttributes();

// Enumerate the blob's metadata.
foreach (var metadataKey in blob.Metadata.Keys)
{
    Console.WriteLine("Metadata name: " + metadataKey.ToString());
    Console.WriteLine("Metadata value: " + blob.Metadata.Get(metadataKey.ToString()));
}

OTHER TIPS

I see that this question is quite old and in the meantime, I guess, the API has changed.

Now, if you want to fetch metadata then you need to use BlobTraits.Metadata option in the following snippet:

await foreach (BlobItem item in containerClient.GetBlobsAsync(BlobTraits.Metadata))
{
    var name = item.Name;
    var meta = item.Metadata;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top