【发布时间】:2020-12-01 08:59:54
【问题描述】:
我正在寻找一种将 Azure 中的 blob 从一个容器移动到另一个容器的方法。我找到的唯一解决方案是使用 Azure 存储数据移动库,但这似乎适用于不同的帐户。我想将同一帐户中的 blob 移动到其他容器。
【问题讨论】:
我正在寻找一种将 Azure 中的 blob 从一个容器移动到另一个容器的方法。我找到的唯一解决方案是使用 Azure 存储数据移动库,但这似乎适用于不同的帐户。我想将同一帐户中的 blob 移动到其他容器。
【问题讨论】:
我没有使用过Azure Storage Data Movement Library,但我很确定它也可以在同一个存储帐户中使用。
关于您的问题,由于 Azure 存储本身不支持 Move 操作,因此您可以通过调用 Copy Blob 后跟 Delete Blob 来实现这一点。通常Copy 操作是异步的,但是当在同一个存储帐户中复制 blob 时,它是同步操作,即复制立即发生。请参阅下面的示例代码:
static void MoveBlobInSameStorageAccount()
{
var cred = new StorageCredentials(accountName, accountKey);
var account = new CloudStorageAccount(cred, true);
var client = account.CreateCloudBlobClient();
var sourceContainer = client.GetContainerReference("source-container-name");
var sourceBlob = sourceContainer.GetBlockBlobReference("blob-name");
var destinationContainer = client.GetContainerReference("destination-container-name");
var destinationBlob = destinationContainer.GetBlockBlobReference("blob-name");
destinationBlob.StartCopy(sourceBlob);
sourceBlob.Delete(DeleteSnapshotsOption.IncludeSnapshots);
}
但是,请记住,此代码仅用于移动同一存储帐户中的 blob。对于跨存储帐户移动 blob,您需要确保在删除源 blob 之前完成复制操作。
【讨论】:
WIndowsAzure.Storage nuget 包。
这对我有用(在@Deumber 发布更好的答案后编辑了答案):
public async Task<CloudBlockBlob> Move(CloudBlockBlob srcBlob, CloudBlobContainer destContainer)
{
CloudBlockBlob destBlob;
if (srcBlob == null)
{
throw new Exception("Source blob cannot be null.");
}
if (!destContainer.Exists())
{
throw new Exception("Destination container does not exist.");
}
//Copy source blob to destination container
string name = srcBlob.Uri.Segments.Last();
destBlob = destContainer.GetBlockBlobReference(name);
await destBlob.StartCopyAsync(srcBlob);
//remove source blob after copy is done.
srcBlob.Delete();
return destBlob;
}
【讨论】:
此问题中接受的答案会将文件移动到您的服务器内存中,然后将其从您的内存中再次上传到 azure。
更好的做法是让所有工作都在 Azure 上完成
CloudBlobClient blobClient = StorageAccount.CreateCloudBlobClient();
CloudBlobContainer sourceContainer = blobClient.GetContainerReference(SourceContainer);
CloudBlobContainer targetContainer = blobClient.GetContainerReference(TargetContainer);
CloudBlockBlob sourceBlob = sourceContainer.GetBlockBlobReference(fileToMove);
CloudBlockBlob targetBlob = targetContainer.GetBlockBlobReference(newFileName);
await targetBlob.StartCopyAsync(sourceBlob);
【讨论】: