DEV Community

LFC
LFC

Posted on

1 1

How to move a Blob to another Container

In this post, I am going to share a method that moves a blob to another container.

This content applies for:

  • Azure Storage Accounts.
  • .NET Core 2.2.
  • Different containers on the same storage account.
public class AzureStorageAccountUtility
{
CloudStorageAccount Account { get; set; }
CloudBlobClient ServiceClient { get; set; }
public AzureStorageAccountUtility(string connectionString)
{
this.Account = CloudStorageAccount.Parse(connectionString);
this.ServiceClient = this.Account.CreateCloudBlobClient();
}
public void MoveBlob(string sourceContainerName, string sourceBlobName, string destinationContainerName, string destinationBlobName)
{
var sourceContainer = ServiceClient.GetContainerReference(sourceContainerName);
var sourceBlob = sourceContainer.GetBlockBlobReference(sourceBlobName);
var destinationContainer = ServiceClient.GetContainerReference(destinationContainerName);
var destinationBlob = destinationContainer.GetBlockBlobReference(destinationBlobName);
destinationBlob.StartCopyAsync(sourceBlob).GetAwaiter().GetResult();
sourceBlob.DeleteAsync().GetAwaiter().GetResult();
}
}

Steps

  1. I have a CloudStorageAccount object that represents the Azure Storage Account.
  2. I have a CloudBlobClient object that represents a Blob service.
  3. In the constructor, CloudStorageAccount and CloudBlobClient are initialized.
  4. MoveBlob method creates a reference of source container and destination container using GetContainerReference method of CloudBlobClient object.
  5. I get a blob reference using GetBlockBlobReference method using the previous containers references.
  6. Finally, I invoke StartCopyAsync method in order to copy the blob to another container, then, the source blob is deleted.

Top comments (1)

Collapse
 
loicsharma profile image
Loïc Sharma

Do note that the copy operation may not be complete by the time "MoveBlob" completes. You will need to poll "destinationBlob.CopyState.Status" (after refreshing attributes using "destinationBlob.FetchAttributesAsync()")!

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more