如何解决重命名 Azure Blob 容器中的文件
我已将文件上传到 Azure Blob 容器。我想使用 DotNet Core Web API 重命名文件而不重新上传文件。
解决方法
我们无法使用 API 直接重命名 blob。现在能想到的解决办法是:
复制 blob 并为其指定正确的名称,然后删除原始 blob。
如果您可以使用 Azure portal
,您可以尝试使用 Storage Explorer
来重命名您的 blob。
这是我发现的实现我的目标
您需要先安装“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;
}
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。