Azure 存储将 blob 移动到其他容器

Azure Storage move blob to other container

我正在寻找一种将 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 之前完成复制操作。

这是对我有用的(在@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);