C#Azure存储从一个blob复制文件到另一个blob

0 upload download azure azure-storage azure-storage-blobs

如何从一个blob读取文件并上传到另一个blob?我的要求是将文件从一个blob复制到另一个具有不同文件名的blob?在C#中

Jua*_*anK 9

实现它的最简单方法是使用" Azure存储数据移动库 "(您可以通过nuget包获得它).

这是一个简单的样本来进行转移:

using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Blob;
using Microsoft.WindowsAzure.Storage.DataMovement;
using System;

namespace BlobClient
{
    class Program
    {
        static void Main(string[] args)
        {
            const string storageConnectionString = "DefaultEndpointsProtocol=https;AccountName=juanktest;AccountKey=loHQwke4lSEu1p2W3gg==";
            const string container1 = "juankcontainer";
            const string sourceBlobName = "test.txt";
            const string destBlobName = "newTest.txt";


            //Setup Account, blobclient and blobs
            CloudStorageAccount account = CloudStorageAccount.Parse(storageConnectionString);
            CloudBlobClient blobClient = account.CreateCloudBlobClient();

            CloudBlobContainer blobContainer = blobClient.GetContainerReference(container1);
            blobContainer.CreateIfNotExists();

            CloudBlockBlob sourceBlob = blobContainer.GetBlockBlobReference(sourceBlobName);

            CloudBlockBlob destinationBlob = blobContainer.GetBlockBlobReference(destBlobName);

            //Setup data transfer
            TransferContext context = new TransferContext();
            Progress<TransferProgress> progress = new Progress<TransferProgress>(
                (transferProgress) => {
                        Console.WriteLine("Bytes uploaded: {0}", transferProgress.BytesTransferred);
                });

            context.ProgressHandler = progress;

            // Start the transfer
            try
            {
                TransferManager.CopyAsync(sourceBlob, destinationBlob, 
                    false /* isServiceCopy */, 
                    null /* options */, context);
            }
            catch (Exception e)
            {
                Console.WriteLine("The transfer is cancelled: {0}", e.Message);
            }

            Console.WriteLine("CloudBlob {0} is copied to {1} ====successfully====", 
                            sourceBlob.Uri.ToString(), 
                            destinationBlob.Uri.ToString());

            Console.ReadLine();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

请注意," Azure存储数据移动库 "非常强大,因此您可以跟踪传输进度,取消操作,甚至暂停它以便以后恢复;)