2
votes

I wrote the following C# code for copying blobs between storage containers in Azure. It doesnt throw any error, but it doesnt give the output either.

static void TransferBlob(string accountName, string accountKey, string containerName, string targetContainerName)

    {
        CloudStorageAccount storageAccount = new CloudStorageAccount(new StorageCredentials(accountName, accountKey), true);
        CloudBlobClient cloudBlobClient = storageAccount.CreateCloudBlobClient();
        CloudBlobContainer sourceContainer = cloudBlobClient.GetContainerReference(containerName);
        CloudBlobContainer targetContainer = cloudBlobClient.GetContainerReference(targetContainerName);
        CloudBlockBlob sourceBlob;
        CloudBlockBlob targetBlob;
        foreach (var blobItem in sourceContainer.ListBlobs())
        {
            sourceBlob = sourceContainer.GetBlockBlobReference(blobItem.Uri.ToString());
            targetBlob = targetContainer.GetBlockBlobReference(blobItem.Uri.ToString());
            targetBlob.StartCopy(sourceBlob);
        }
    }
1
Which nuget package and version are you using for Azure Storage?juvchan

1 Answers

3
votes

You need to use useFlatBlobListing: true and blob.Name.

static void TransferBlob(string accountName, string accountKey, string sourceContainerName, string targetContainerName)
{
    CloudStorageAccount storageAccount = new CloudStorageAccount(new StorageCredentials(accountName, accountKey), true);
    CloudBlobClient cloudBlobClient = storageAccount.CreateCloudBlobClient();
    CloudBlobContainer sourceContainer = cloudBlobClient.GetContainerReference(sourceContainerName);
    CloudBlobContainer targetContainer = cloudBlobClient.GetContainerReference(targetContainerName);
    if (sourceContainer.Exists() && targetContainer.Exists())
    {
        foreach (IListBlobItem item in sourceContainer.ListBlobs(useFlatBlobListing: true))
        {
            var blob = item as CloudBlockBlob;
            if (blob != null)
            {
                CloudBlockBlob sourceBlob = sourceContainer.GetBlockBlobReference(blob.Name);
                CloudBlockBlob targetBlob = targetContainer.GetBlockBlobReference(blob.Name);
                targetBlob.StartCopy(sourceBlob);
            }
        }
    }
}