I want to delete all the files from a particular S3 bucket. The files exist in a folder called "test" inside S3 bucket. I couldn't figure out how to delete all the files inside the S3 bucket in a loop. I am not sure what parameters can I pass to DeleteObjectsAsync in order to delete the files. This is what I have so far after reading some online AWS documents:
using (var client = new AmazonS3Client(_configuration["AwsAccesKey"].ToString(), _configuration["AwsSecretKey"].ToString()))
{
var request = new ListObjectsRequest
{
BucketName = _configuration["AwsBucketName"].ToString()
};
var response = await client.ListObjectsAsync(request);
foreach (var entry in response.S3Objects)
{
await client.DeleteObjectsAsync(request, entry.Key);
}
}
return View();
User has been asking me to delete all the files whenever they click the button on the front end.This is not dependent on duration.
Any help on this will be appreciated.
CodePudding user response:
The DeleteObjectsAsync method excepts DeleteObjectsRequest which should contain all the keys to objects you want to delete.
Your code should be something like this:
var request = new ListObjectsRequest
{
BucketName = "bucketname"
};
var response = await client.ListObjectsAsync(request);
var keys = new List<KeyVersion>();
foreach (var item in response.S3Objects)
{
// Here you can provide VersionId as well.
keys.Add(new KeyVersion { Key = item.Key });
}
var multiObjectDeleteRequest = new DeleteObjectsRequest()
{
BucketName = "bucketname",
Objects = keys
};
var deleteObjectsResponse = await client.DeleteObjectsAsync(multiObjectDeleteRequest);
It's important to note that the ListObjectsAsync returns at most 1000 objects. DeleteObjectsRequest deletes at most 1000 objects.
You can read more here: https://docs.aws.amazon.com/AmazonS3/latest/userguide/delete-multiple-objects.html
