0

I have the following code:

CloudStorageAccount storageAccount = CloudStorageAccount.Parse(Environment.GetEnvironmentVariable("AzureWebJobsStorage"));
CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
CloudBlobContainer blobContainer = blobClient.GetContainerReference("images");
CloudBlockBlob blockBlob = blobContainer.GetBlockBlobReference(filename);

using (var stream = new MemoryStream(imageBytes))
{
    blockBlob.Properties.ContentType = contentType;

    blockBlob.Metadata.Add("MyMetadataProperty1", "MyMetadataValue1");
    blockBlob.Metadata.Add("MyMetadataProperty2", "MyMetadataValue2");
    blockBlob.Metadata.Add("MyMetadataProperty3", "MyMetadataValue3");
    blockBlob.Metadata.Add("MyMetadataProperty", "MyMetadataValue4");
    // await blockBlob.SetMetadataAsync(); // Microsoft.WindowsAzure.Storage: The specified blob does not exist.

    await blockBlob.UploadFromStreamAsync(stream);
}

I can't setup metadata on the upload time.

If I call await blockBlob.SetMetadataAsync(); before UploadFromStreamAsync(), I get error: Microsoft.WindowsAzure.Storage: The specified blob does not exist.

I found some articles in the Internet that I can do that: here and here.

Library that I use:

<PackageReference Include="Microsoft.Azure.WebJobs.Extensions.Storage" Version="3.0.10" />

Any ideas why I have this error?

Vlad
  • 852
  • 10
  • 23

1 Answers1

3

Check the description about this method: SetMetadataAsync.

Initiates an asynchronous operation to update the blob's metadata.

It's used to update the metadata, so actually if you want to set the metadata when you upload the blob, just set blockBlob.Metadata.Add(key, value) or blockBlob.Metadata[key] = "value". The below is my test code.

        CloudStorageAccount storageAccount = CloudStorageAccount.Parse("connection string");
        CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
        CloudBlobContainer blobContainer = blobClient.GetContainerReference("test");
        CloudBlockBlob blockBlob = blobContainer.GetBlockBlobReference("1.txt");

        var filePath = "C:\\Users\\georgec\\Downloads\\test.txt";
        FileStream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read);
        blockBlob.Metadata["mymetadata"] = "mymetadatavalue";
        //blockBlob.SetMetadataAsync();
        await blockBlob.UploadFromStreamAsync(fileStream);

enter image description here

George Chen
  • 13,703
  • 2
  • 11
  • 26
  • The problem was that if you want to add another metadata later without calling `await blob.FetchAttributesAsync()`, it override's all metadata. Plus, in another function with `[BlobTrigger]` you should still use `FetchAttributesAsync` to get access to the metadata. – Vlad Nov 25 '19 at 09:28
  • Does setting metadata will work in the same way for `OpenWriteAsync` and `CommitAsync`? – Gautam Kumar Samal May 17 '21 at 06:46