shl*_*chz 6 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);
}
Run Code Online (Sandbox Code Playgroud)
我收到"未找到"错误.我确实知道源blob确实存在.我使用了错误的命令吗?关于存储帐户之间的复制,我有什么遗漏吗?
shl*_*chz 10
在玩完代码之后,我找到了答案.只有当源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);
Run Code Online (Sandbox Code Playgroud)
希望它能帮助将来的某个人.
您还可以使用流在存储帐户之间复制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);
}
}
Run Code Online (Sandbox Code Playgroud)