Skip to main content

Delete Multiple Objects of a Bucket

Components

using Amazon;
using Amazon.S3;
using Amazon.S3.Model;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace DeleteObjects
{
class DeleteObjects
{
private const string bucketName = "<BUCKET_NAME>";
private static IAmazonS3 _s3Client;
public static void Main()
{
var awsCredentials = new Amazon.Runtime.BasicAWSCredentials("<ACCESS-KEY>", "<SECRET-KEY>");
var config = new AmazonS3Config { ServiceURL = "<ENDPOINT>" };
_s3Client = new AmazonS3Client(awsCredentials, config);
DeleteObjectsAsync().Wait();
}
private static async Task DeleteObjectsAsync()
{
DeleteObjectsRequest request = new DeleteObjectsRequest
{
BucketName = bucketName,
Objects = new List<KeyVersion>
{
new KeyVersion() {Key = "Item1"},
// Versioned item
new KeyVersion() { Key = "Item2", VersionId = "Rej8CiBxcZKVK81cLr39j27Y5FVXghDK", },
// Item in subdirectory
new KeyVersion() { Key = "Logs/error.txt"}
}
};
try
{
await _s3Client.DeleteObjectsAsync(request);

Console.WriteLine($"Objects successfully deleted from {bucketName} bucket");
}
catch (AmazonS3Exception amazonS3Exception)
{
Console.WriteLine("An AmazonS3Exception was thrown. Exception: " + amazonS3Exception.ToString());
}
catch (Exception e)
{
Console.WriteLine("Exception: " + e.ToString());
}
}
}
}