I have files uploaded to Azure Blob Container. I want to rename the files using DotNet Core Web API without re-uploading the files.
This is what I found to achieve my objective
You need to install "Azure.Storage.Blobs" NuGet first
[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;
}
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.