我正在寻找一种方法将Azure中的blob从一个容器移动到另一个容器。我找到的唯一解决方案是使用Azure存储数据移动库,但这似乎适用于不同的帐户。我想将同一帐户中的blob移动到另一个容器中。
答案 0 :(得分:24)
我没有使用过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之前完成复制操作。
答案 1 :(得分:15)
此问题中接受的答案将文件移动到您的服务器内存,然后再次将文件上传到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);
答案 2 :(得分:14)
这对我有用(在@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;
}