在存储帐户之间复制blob

时间:2016-04-13 13:21:47

标签: c# azure-storage azure-storage-blobs

我尝试将blob从一个存储帐户复制到另一个存储帐户(位于其他位置)。

我使用以下代码:

var sourceContainer = sourceClient.GetContainerReference(containerId);
var sourceBlob = sourceContainer.GetBlockBlobReference(blobId);
if (await sourceBlob.ExistsAsync().ConfigureAwait(false))
{
    var targetContainer = targetClient.GetContainerReference(containerId);
    await targetContainer.CreateIfNotExistsAsync().ConfigureAwait(false);
    var targetBlob = targetContainer.GetBlockBlobReference(blobId);
    await targetBlob.DeleteIfExistsAsync().ConfigureAwait(false);
    await targetBlob.StartCopyAsync(sourceBlob).ConfigureAwait(false);
}

我得到一个" Not Found"错误。 我确实知道源blob确实存在。 我使用了错误的命令吗?关于存储帐户之间的复制,我有什么遗漏吗?

2 个答案:

答案 0 :(得分:9)

在玩完代码之后,我找到了答案。 只有当源blob是uri而不是blob引用时,才能在存储帐户之间进行复制。 以下代码有效:

var sourceContainer = sourceClient.GetContainerReference(containerId);
var sourceBlob = sourceContainer.GetBlockBlobReference(blobId);
// Create a policy for reading the blob.
var policy = new SharedAccessBlobPolicy
{
    Permissions = SharedAccessBlobPermissions.Read,
    SharedAccessStartTime = DateTime.UtcNow.AddMinutes(-15),
    SharedAccessExpiryTime = DateTime.UtcNow.AddDays(7)
};
// Get SAS of that policy.
var sourceBlobToken = sourceBlob.GetSharedAccessSignature(policy);
// Make a full uri with the sas for the blob.
var sourceBlobSAS = string.Format("{0}{1}", sourceBlob.Uri, sourceBlobToken);
var targetContainer = targetClient.GetContainerReference(containerId);
await targetContainer.CreateIfNotExistsAsync().ConfigureAwait(false);
var targetBlob = targetContainer.GetBlockBlobReference(blobId);
await targetBlob.DeleteIfExistsAsync().ConfigureAwait(false);
await targetBlob.StartCopyAsync(new Uri(sourceBlobSAS)).ConfigureAwait(false);

希望将来会帮助某人。

答案 1 :(得分:3)

您还可以使用流在存储帐户之间复制Blob:

var sourceContainer = sourceClient.GetContainerReference(sourceContainer);
var sourceBlob = sourceContainer.GetBlockBlobReference(sourceBlobId);
var targetContainer = targetClient.GetContainerReference(destContainer);
var targetBlob = targetContainer.GetBlockBlobReference(destBlobId);

using (var targetBlobStream = await targetBlob.OpenWriteAsync())
{
    using (var sourceBlobStream = await sourceBlob.OpenReadAsync())
    {
        await sourceBlobStream.CopyToAsync(targetBlobStream);
    }
}