如何使用 Azure 存储 SDK 将 Azure 文件存储上的文件从一个子文件夹移动到另一个子文件夹?

How to move a file on Azure File Storage from one sub folder to another sub folder using the Azure Storage SDK?

我正在尝试弄清楚如何将 Azure 文件存储中的文件从一个位置移动到另一个位置,在同一共享中。

例如

source -> \Share1\someFile.txt
destination -> \Share1\Foo\Bar\someFile.txt

干杯!

Azure 存储文件共享是与 SMB 兼容的共享。所以你应该能够用正常的文件I/O操作来制作文件copies/moves。这与直接 blob 操作相反,在直接 blob 操作中,您需要通过 Storage API.

专门创建容器、启动 blob 副本等。

Azure blob 子控制器是一个虚拟功能,因为它们实际上并不存在,blob/file 的名称包含完整路径。因此,您不必明确 "create" 目录。

我认为 Azure blobs/files 不存在原子 "rename" 方法...要绕过它,您必须复制(使用新名称)然后删除原始方法.

这是documented in the Getting Started guide on Azure Storage Files参考。

您需要的是 StartCopy 将文件从一个位置复制到另一个位置的方法。

// Start the copy operation.
destinationFile.StartCopy(sourceFile);

而且,是的,如果目标目录不存在,您将必须创建它。

遗憾的是,我们没有通过客户端 SDK 所依赖的 REST API 公开的移动/重命名功能。您当然可以通过 SMB 执行这些功能。我们的积压工作中确实有这些功能,但还没有实施的时间表。

像这样:

public static void MoveTo(this CloudFile source, CloudFileDirectory directory)
{
    var target = directory.GetFileReference(source.Name);
    target.StartCopy(source);
    source.Delete();
}

这是 Asp.net Core 3+ 的更新答案,带有新的 blob API。您可以使用 BlockBlobClient with StartCopyFromUriAsync and if you want to await completion WaitForCompletionAsync

var blobServiceClient = new BlobServiceClient("StorageConnectionString");
var containerClient = blobServiceClient.GetBlobContainerClient(container);
var blobs = containerClient.GetBlobs(BlobTraits.None, BlobStates.None, sourceFolder);

await Task.WhenAll(blobs.Select(async blob =>
{
    var targetBlobClient = containerClient.GetBlockBlobClient($"{targetFolder}/{blob.Name}");
    var blobUri = new Uri($"{containerClient.Uri}/{blob.Name}");
    var copyOp = await targetBlobClient.StartCopyFromUriAsync(blobUri);
    return await copyOp.WaitForCompletionAsync();
}).ToArray());

或者如果您不需要等待完成而只想"fire and forget"。

foreach (var blob in blobs)
{
    var targetBlobClient = containerClient.GetBlockBlobClient($"{targetFolder}/{blob.Name}");
    var blobUri = new Uri($"{containerClient.Uri}/{blob.Name}");
    targetBlobClient.StartCopyFromUriAsync(blobUri);
}