Vlad
Vlad

Reputation: 873

Can't set Azure Block Blob Metadata on upload time

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?

Upvotes: 0

Views: 1588

Answers (1)

George Chen
George Chen

Reputation: 14324

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

Upvotes: 3

Related Questions