c# - 将一个Azure Blob复制到Azure Storage Client 2.0中的另一个Blob




4 Answers

Gaurav Mantri在2.0版本上撰写了一系列有关Azure存储的文章。 我从他的Storage Client Library 2.0博客文章中获取了这段代码摘录- 迁移 Blob Copy的Blob存储代码

    CloudStorageAccount storageAccount = new CloudStorageAccount(new StorageCredentials(accountName, accountKey), true);
CloudBlobClient cloudBlobClient = storageAccount.CreateCloudBlobClient();
CloudBlobContainer sourceContainer = cloudBlobClient.GetContainerReference(containerName);
CloudBlobContainer targetContainer = cloudBlobClient.GetContainerReference(targetContainerName);
string blobName = "<Blob Name e.g. myblob.txt>";
CloudBlockBlob sourceBlob = sourceContainer.GetBlockBlobReference(blobName);
CloudBlockBlob targetBlob = targetContainer.GetBlockBlobReference(blobName);
targetBlob.StartCopyFromBlob(sourceBlob);

在旧的1.7存储客户端中,有一个CloudBlob.CopyFromBlob(otherBlob)方法,但它似乎不存在于2.0版本中。 复制blob的建议最佳做法是什么? 我确实看到了ICloudBlob.BeginStartCopyFromBlob方法。 如果这是合适的方法,我该如何使用它?




由于BeginStartCopyBlob函数不再存在,因此不再适用于SDK的最新版本(7.x)的FYI。

你可以这样做:

// this tunnels the data via your program,
// so it reuploads the blob instead of copying it on service side
using (var stream = await sourceBlob.OpenReadAsync())
{
  await destinationBlob.UploadFromStreamAsync(stream);
}

编辑:由Talon

如@(Alexey Shcherbak)所述,这是一个更好的方法:

targetCloudBlob.StartCopy(sourceCloudBlob.Uri);
or
targetCloudBlob.StartCopyAsync(sourceCloudBlob.Uri);

while (targetCloudBlob.CopyState.Status == CopyStatus.Pending)
{
    Thread.Sleep(500);
}

if (targetCloudBlob.CopyState.Status != CopyStatus.Success)
{
    throw new Exception("Copy failed: " +    targetCloudBlob.CopyState.Status);
}



对我来说,WindowsAzure.Storage 8.0.1,James Hancock的解决方案完成了服务器端复制,但客户端复制状态仍然停留在Pending (永远循环)。 解决方案是在Thread.sleep(500)之后在targetCloudBlob上调用FetchAttributes() Thread.sleep(500)

// Aaron Sherman's code 

targetCloudBlob.StartCopy(sourceCloudBlob.Uri);

while (targetCloudBlob.CopyState.Status == CopyStatus.Pending)
{
    Thread.Sleep(500);
    targetCloudBlob.FetchAttributes();
}

// James Hancock's remaining code

官方Microsoft文档(异步示例)




这是我简短的简单回答。

public void Copy(CloudBlockBlob srcBlob, CloudBlobContainer destContainer)
{
    CloudBlockBlob destBlob;

    if (srcBlob == null)
    {
        throw new Exception("Source blob cannot be null.");
    }

    if (!destContainer.Exists())
    {
        throw new Exception("Destination container does not exist.");
    }

    //Copy source blob to destination container
    string name = srcBlob.Uri.Segments.Last();
    destBlob = destContainer.GetBlockBlobReference(name);
    destBlob.StartCopyAsync(srcBlob);                
}



Related

c# azure azure-storage