【问题标题】:Rename files in Azure Blob Container重命名 Azure Blob 容器中的文件
【发布时间】:2021-05-25 09:21:14
【问题描述】:

我已将文件上传到 Azure Blob 容器。我想使用 DotNet Core Web API 重命名文件而不重新上传文件。

【问题讨论】:

  • 我认为这是不可能的,blob存储api没有这种方法。

标签: c# .net-core azure-blob-storage


【解决方案1】:

我们无法使用 API 直接重命名 blob。现在能想到的解决办法是:

复制 blob 并为其命名,然后删除原始 blob。

如果您可以使用Azure portal,您可以尝试使用Storage Explorer 重命名您的blob。

【讨论】:

  • 我很难想出 Azure 中有什么可以重命名的;这个答案很有意义。
  • 我想使用 DotNet Core Web API 重命名文件。转到存储资源管理器重命名文件是不切实际的
【解决方案2】:

这就是我发现实现目标的方法

您需要先安装“Azure.Storage.Blobs”NuGet

[HttpPost]
[ActionName("Rename")]
public async Task Rename([FromBody] List<FileToRename> files)
{
    string connStr = "<Azure Blob Connection String>";
  
    BlobContainerClient container = new BlobContainerClient(connStr, files[0].ContainerName);

    foreach (FileToRename file in files)
    {
        try
        {
            BlobClient sourceBlob = container.GetBlobClient(file.SourceFilename);

            // Ensure that the source blob exists.
            if (await sourceBlob.ExistsAsync())
            {
                // Lease the source blob for the copy operation
                // to prevent another client from modifying it.
                BlobLeaseClient lease = sourceBlob.GetBlobLeaseClient();
                // Specifying -1 for the lease interval creates an infinite lease.
                await lease.AcquireAsync(TimeSpan.FromSeconds(-1));

                // Get the source blob's properties and display the lease state.
                BlobProperties sourceProperties = await sourceBlob.GetPropertiesAsync();
                Console.WriteLine($"Lease state: {sourceProperties.LeaseState}");

                // Get a BlobClient representing the destination blob with a unique name.
                BlobClient destBlob = container.GetBlobClient(file.DestinationFilename);

                // Start the copy operation.
                await destBlob.StartCopyFromUriAsync(sourceBlob.Uri);

                // Update the source blob's properties.
                sourceProperties = await sourceBlob.GetPropertiesAsync();

                if (sourceProperties.LeaseState == LeaseState.Leased)
                {
                    // Break the lease on the source blob.
                    await lease.BreakAsync();

                    // Update the source blob's properties to check the lease state.
                    sourceProperties = await sourceBlob.GetPropertiesAsync();
                    Console.WriteLine($"Lease state: {sourceProperties.LeaseState}");
                }
            }

            await sourceBlob.DeleteAsync(DeleteSnapshotsOption.IncludeSnapshots);
            file.IsSuccess = true;
        }
        catch (Exception ex)
        {
            file.IsSuccess = false;
            file.Message = ex.Message;
        }
    }
}

【讨论】:

    猜你喜欢
    • 2020-03-27
    • 1970-01-01
    • 2017-07-31
    • 2013-04-13
    • 2014-06-22
    • 1970-01-01
    • 2021-09-11
    • 1970-01-01
    相关资源
    最近更新 更多