Skip to content

Instantly share code, notes, and snippets.

@NewFuture
Created November 14, 2022 10:05
Show Gist options
  • Save NewFuture/593dd8dd204af451bedc353ef2282383 to your computer and use it in GitHub Desktop.
Save NewFuture/593dd8dd204af451bedc353ef2282383 to your computer and use it in GitHub Desktop.
// dotnet add package Azure.Storage.Blobs
// dotnet add package Azure.Storage.Blobs.Batch
using Azure.Storage.Blobs;
using Azure.Storage.Blobs.Models;
using Azure.Storage.Blobs.Specialized;
// Get a connection string to our Azure Storage account.
const string connectionString = "";
const string containerName = "";
const string prefix = "";
// < 256
const int MAX_BATCH = 250;
// Get a reference to a container named "sample-container" and then create it
BlobServiceClient service = new BlobServiceClient(connectionString);
BlobContainerClient containerClinet = service.GetBlobContainerClient(containerName);
BlobBatchClient batch = service.GetBlobBatchClient();
var blobItems = containerClinet.GetBlobsAsync(prefix: prefix);
var counter = 0;
var list = new List<string>();
Console.WriteLine("batch delete!");
await foreach (var blobItem in blobItems)
{
list.Add(blobItem.Name);
Console.WriteLine(blobItem.Name.Substring(prefix.Length));
if (list.Count >= MAX_BATCH)
{
var task = list;
list = new List<string>();
await BatchDelete(task);
};
}
await BatchDelete(list);
async Task BatchDelete(List<string> items)
{
Console.WriteLine("task start");
await batch.DeleteBlobsAsync(items.Select(i => new Uri(containerClinet.Uri + "/" + i)));
counter += items.Count;
Console.WriteLine($"${items.Count} tasks done, total ${counter}");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment