复制 Azure Blob 及其元数据

Copy Azure Blob and its metadata

所以我想将一个 Azure blob 及其元数据复制到一个新的 blob。 我有方法

public void CopyBlob(CloudBlockBlob blob, CloudBlockBlob newBlob)
{
     CopyStatus copy = CopyStatus.Pending;
     while (copy != CopyStatus.Success)
     {
           newBlob.StartCopyFromBlob(blob);
           copy = CheckIsDoneCopying(newBlob, "MyContainerName");
     }
}

public CopyStatus CheckIsDoneCopying(CloudBlockBlob blob, string containerName)
{
    while (blob.CopyState.Status == CopyStatus.Pending)
    {
        Thread.Sleep(TimeSpan.FromSeconds(20));
        blob = GetBlob(blob.Name, containerName);
    }
    return blob.CopyState.Status;
}

这些方法适用于复制 blob,但不会将现有元数据从我现有的 blob 复制到新的。这可能吗?

所以我不得不自己实现这个。我认为通过 CopyFromBlob 方法上的选项会有更简单的方法来执行此操作,但显然不是。 所以在 blob 完成复制后添加:

blob.FetchAttributes();
foreach (var attribute in blob.Metadata)
{
    if (newBlob.Metadata.ContainsKey(attribute.Key))
    {
         newBlob.Metadata[attribute.Key] = attribute.Value;
    }
    else
    {
         newBlob.Metadata.Add(new KeyValuePair<string, string>(attribute.Key, attribute.Value));
    }
}
newBlob.SetMetadata();

这会将所有元数据从旧 blob 复制到新 blob。

查看 Copy Blob 的 REST API 文档时,有一件事引起了我的注意(在 Request Headers 部分下,x-ms-meta-name:value):

If no name-value pairs are specified, the operation will copy the source blob metadata to the destination blob. If one or more name-value pairs are specified, the destination blob is created with the specified metadata, and metadata is not copied from the source blob.

现在,当我查看您的源代码时,您实际上是在复制之前在新 blob 上设置元数据。

newBlob.FetchAttributes();
if (newBlob.Metadata.ContainsKey(StorageManager.IsLive))
{
    newBlob.Metadata[StorageManager.IsLive] = "N";
}
else
{
    newBlob.Metadata.Add(new KeyValuePair<string, string>(StorageManager.IsLive, "N"));
} 

由于新 blob 的元数据已经存在,因此复制 blob 操作不会将元数据从源 blob 复制到目标。

如果删除上面的代码,源 blob 中的元数据应该被复制到新的 blob。