无法在上传时间设置Azure Block Blob元数据

时间:2019-11-23 08:56:38

标签: c# azure azure-storage-blobs

我有以下代码:

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);
}

我无法在上传时间设置元数据。

如果我在await blockBlob.SetMetadataAsync();之前致电UploadFromStreamAsync(),则会收到错误消息:Microsoft.WindowsAzure.Storage: The specified blob does not exist.

我在互联网上找到了一些可以做到的文章:herehere

我使用的图书馆:

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

我为什么会有这个错误的任何想法?

1 个答案:

答案 0 :(得分:1)

检查有关此方法的描述:SetMetadataAsync

  

启动异步操作以更新Blob的元数据。

它用于更新元数据,因此实际上,如果要在上载Blob时设置元数据,只需设置blockBlob.Metadata.Add(key, value)blockBlob.Metadata[key] = "value"。下面是我的测试代码。

        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