Search code examples
.netazureazure-blob-storagevhd

Azure Resource Manager .NET SDK, copying VHDs/Blobs


I am trying to find a way to copy a VHD to my storage account in my resource group.

I have a Sas Uri of a VHD.

I Powershell I would use:

Start-AzureStorageBlobCopy `
-AbsoluteUri $sas.AccessSAS `
-DestContainer 'vhds' -DestContext $destContext -DestBlob 'MyDestinationBlobName.vhd'

to do that.

I can't seem to find a way to do it from .NET SDK of Azure Resource Manager. https://github.com/Azure/azure-sdk-for-net/tree/AutoRest/src/ResourceManagement/

Is there any way I can copy a blob using .NET?


Solution

  • Is there any way I can copy a blob using .NET?

    You would need to use Azure Storage SDK for .Net (Github|Nuget).

    using Microsoft.WindowsAzure.Storage;
    using Microsoft.WindowsAzure.Storage.Auth;
    using Microsoft.WindowsAzure.Storage.Blob;
    
        static void CopyBlobUsingSasExample()
        {
            var destinationAccountName = "";
            var destinationAccountKey = "";
            var destinationAccount = new CloudStorageAccount(new StorageCredentials(destinationAccountName, destinationAccountKey), true);
            var destinationContainerName = "vhds";
            var destinationContainer = destinationAccount.CreateCloudBlobClient().GetContainerReference(destinationContainerName);
            destinationContainer.CreateIfNotExists();
            var destinationBlob = destinationContainer.GetPageBlobReference("MyDestinationBlobName.vhd");
            var sourceBlobSasUri = "";
            destinationBlob.StartCopy(new Uri(sourceBlobSasUri));
            //Since copy operation is async, please wait for the copy operation to finish.
            do
            {
                destinationBlob.FetchAttributes();
                var copyStatus = destinationBlob.CopyState.Status;
                if (copyStatus != CopyStatus.Pending)
                {
                    break;
                }
                else
                {
                    System.Threading.Thread.Sleep(5000);//Sleep for 5 seconds and then fetch attributes to check the copy status.
                }
            } while (true);
        }