我正在使用此代码将blob从一个帐户复制到另一个帐户......但它会引发异常。
var srcAccount = CloudStorageAccount.Parse("connection string 1");
var dstAccount = CloudStorageAccount.Parse("connection string 2");
var srcBlobClient = srcAccount.CreateCloudBlobClient();
var dstBlobClient = dstAccount.CreateCloudBlobClient();
foreach (var srcCloudBlobContainer in srcBlobClient.ListContainers())
{
var dstCloudBlobContainer = dstBlobClient
.GetContainerReference(srcCloudBlobContainer.Name);
dstCloudBlobContainer.CreateIfNotExists();
foreach (var srcBlob in srcCloudBlobContainer.ListBlobs())
{
if (srcBlob.GetType() == typeof(CloudBlockBlob))
{
var srcBlockBlock = (CloudBlockBlob)srcBlob;
var dstBlockBlock = dstCloudBlobContainer
.GetBlockBlobReference(srcBlockBlock.Name);
// throws exception StorageException:
// The remote server returned an error: (404) Not Found.
dstBlockBlock.StartCopyFromBlob(srcBlockBlock.Uri);
}
}
}
Microsoft声明支持跨帐户副本,但我无法让它工作。
我做错了什么?
答案 0 :(得分:9)
您可以检查源blob容器的ACL吗?如果是 Private
,您可能需要将ACL更改为 Public
/ Blob
或创建SAS URL。如果您希望将blob容器的ACL保留为Private
并使用SAS URL,则可以使用以下代码:
var srcAccount = CloudStorageAccount.Parse("connection string 1");
var dstAccount = CloudStorageAccount.Parse("connection string 2");
var srcBlobClient = srcAccount.CreateCloudBlobClient();
var dstBlobClient = dstAccount.CreateCloudBlobClient();
foreach (var srcCloudBlobContainer in srcBlobClient.ListContainers())
{
var dstCloudBlobContainer = dstBlobClient
.GetContainerReference(srcCloudBlobContainer.Name);
dstCloudBlobContainer.CreateIfNotExists();
//Assuming the source blob container ACL is "Private", let's create a Shared Access Signature with
//Start Time = Current Time (UTC) - 15 minutes to account for Clock Skew
//Expiry Time = Current Time (UTC) + 7 Days - 7 days is the maximum time allowed for copy operation to finish.
//Permission = Read so that copy service can read the blob from source
var sas = srcCloudBlobContainer.GetSharedAccessSignature(new SharedAccessBlobPolicy()
{
SharedAccessStartTime = DateTime.UtcNow.AddMinutes(-15),
SharedAccessExpiryTime = DateTime.UtcNow.AddDays(7),
Permissions = SharedAccessBlobPermissions.Read,
});
foreach (var srcBlob in srcCloudBlobContainer.ListBlobs())
{
if (srcBlob.GetType() == typeof(CloudBlockBlob))
{
var srcBlockBlock = (CloudBlockBlob)srcBlob;
var dstBlockBlock = dstCloudBlobContainer
.GetBlockBlobReference(srcBlockBlock.Name);
//Create a SAS URI for the blob
var srcBlockBlobSasUri = string.Format("{0}{1}", srcBlockBlock.Uri, sas);
// throws exception StorageException:
// The remote server returned an error: (404) Not Found.
dstBlockBlock.StartCopyFromBlob(new Uri(srcBlockBlobSasUri));
}
}
}