重命名Azure Blob容器中的文件



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

这是我发现实现我的目标

你需要安装" azure . storage . blob "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;
}
}
}

最新更新