Saturday 26 October 2024

Copy Blob Between Azure Storage Accounts with C# Using DefaultAzureCredential

 Copying a blob between Azure storage account without downloading the blob locally is realy simple with azcopy command. Now using Azure.Storage.Blobs we can copy blobs between Azure sotrages without downloading the blob locally, with C# code as well. Using DefaultAzureCredential for the copy operation is useful, when we use apps with managed identities, such as workload identity in AKS. Let's explore steps necessary to copy a blob from one storage account to another with C# console app.

How it works

When the example simple console app is executed it copies blob from sourse storage account to target storage account as shown below.



Steps to implement

For the source storage account the executing user (or managed identity) need to be given the "Blob Data Reader" role as a minimum. For the traget storage account the user or the managed identity need "Blob Data Contributor" permission.

In the console app refer below two nuget packages.

<Project Sdk="Microsoft.NET.Sdk">

    <PropertyGroup>
        <OutputType>Exe</OutputType>
        <TargetFramework>net8.0</TargetFramework>
        <ImplicitUsings>enable</ImplicitUsings>
        <Nullable>enable</Nullable>
    </PropertyGroup>

    <ItemGroup>
        <PackageReference Include="Azure.Identity" Version="1.13.1" />
        <PackageReference Include="Azure.Storage.Blobs" Version="12.22.2" />
    </ItemGroup>

</Project>

Then in the console app Program.cs use below usings.

using Azure.Storage.Blobs.Models;
using Azure.Storage.Blobs;
using Azure.Identity;
using Azure;
using Azure.Storage.Sas;

As the next step we can define the variables for source storage blob and destination as below.


We can define DefaultAzureCredential and create BlobServiceClients for both source and destination storage accounts.


Next we can get the BlobClient for the source blob. When using DefaultAzureCredentils we have to generate the SAS (shared access signature) Uri for the source blob to copyy from, using a user delegation key for the running user (or the managed identity)


Using the generated SAS Uri we can start copying the blob asynchronously to the destonation storage account. Then we can check the copy progress and verify success copy status or identify if the reason if the copy opraton failed as shown below. The full example code is availabe here in GitHub. For further information refer the documentation here.







No comments:

Popular Posts