首页 > 解决方案 > 使用 c# 代码在 azure storage account gen 2 之间复制大文件

问题描述

我们将文件存储在 azure storage account gen 2 中

我们正在使用 api 方法来创建、删除和读取文件 [如在此处提到的 读取文件]

我们正在尝试使用 api 方法将文件从一个存储帐户复制到另一个。有人可以建议实现它的快速方法吗?

笔记:

标签: c#azure.net-coreazure-storageazure-storage-files

解决方案


实际上,很难找到有效的解决方案,因为官方文档已经过时并且那里缺乏任何最新的示例。

过时的方式

可以在此处找到使用 blob 容器的过时示例:https ://docs.microsoft.com/en-us/azure/storage/blobs/storage-quickstart-blobs-dotnet?tabs=windows

该示例使用已重命名并拆分为单独包的WindowsAzure.StorageNuGet 包。Microsoft.Azure.Storage.*

最新的解决方案

我目前正在将静态 SPA 部署到 Azure Blob 存储。它有一个非常好的功能“静态网站”来提供文件。

有一个工作示例可用于将所有内容从一个 blob 容器复制到另一个容器。请将其视为提示(未准备好生产)。

您只需要:

  • 有一个现有的 blob 容器。
  • 安装Microsoft.Azure.Storage.DataMovementNuGet 包。
  • 提供正确的连接字符串。

这是代码:

// I left fully qualified names of the types to make example clear.

var connectionString = "Connection string from `Azure Portal > Storage account > Access Keys`";

var sourceContainerName = "<source>";
var destinationContainerName = "<destination>";

var storageAccount = Microsoft.Azure.Storage.CloudStorageAccount.Parse(connectionString);

var client = storageAccount.CreateCloudBlobClient();

var sourceContainer = client.GetContainerReference(sourceContainerName);

var destinationContainer = client.GetContainerReference(destinationContainerName);
// Create destination container if needed
await destinationContainer.CreateIfNotExistsAsync();

var sourceBlobDir = sourceContainer.GetDirectoryReference(""); // Root directory
var destBlobDir = destinationContainer.GetDirectoryReference("");

// Use UploadOptions to set ContentType of destination CloudBlob
var options = new Microsoft.Azure.Storage.DataMovement.CopyDirectoryOptions
{
    Recursive = true,
};

var context = new Microsoft.Azure.Storage.DataMovement.DirectoryTransferContext();

// Perform the copy
var transferStatus = await Microsoft.Azure.Storage.DataMovement.TransferManager
    .CopyDirectoryAsync(sourceBlobDir, destBlobDir, true, options, context);

推荐阅读