简体   繁体   中英

Copy blobs between storage containers in Azure using C#

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);
        }
    }

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);
            }
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM