Reputation: 335
I am looking for a better way to delete an S3 Bucket.
AWS SDK for .Net does not allow to delete a non-empty bucket and
doesn't have any overloaded DeleteBucket()
to delete any child objects in the bucket.
This is the way I am currently deleting a bucket -
//Delete all objects in the bucket first - a non-empty bucket can't be deleted
using (ListObjectsResponse response = amazonS3Client.ListObjects(new ListObjectsRequest().WithBucketName(bucket.Name)))
{
if (response.S3Objects.Count > 0)
{
List<KeyVersion> keys = response.S3Objects.Select(obj => new KeyVersion(obj.Key)).ToList();
DeleteObjectsRequest deleteObjectsRequest = new DeleteObjectsRequest
{
BucketName = bucket.Name,
Keys = keys
};
amazonS3Client.DeleteObjects(deleteObjectsRequest);
}
}
//Delete Bucket
DeleteBucketRequest request = new DeleteBucketRequest
{
BucketName = bucket.Name
};
amazonS3Client.DeleteBucket(request);
Is any better way to delete a bucket in S3 - where I don't need to fetch the objects first.
Is there any method that I am missing in AWS SDK for .Net?
Thank you!
Upvotes: 1
Views: 4823
Reputation: 310
In case anyone is still interested in this old question. And someone stumbles across it like I did. Especially someone that uses .Net core for S3 interaction.
In the meantime official AWS S3 Utils class emerged which has function called DeleteS3BucketWithObjectsAsync and supports deleting the bucket with all its objects. The official documentation can be found here
It is part of the AmazonS3Util namespace from the AWSSDK.S3 nuget package.
Upvotes: 4
Reputation: 6654
It's easier to do it directly without the API. There is a very easy way to delete a bucket in S3 using the "Lifecycle" settings using the S3 Management Console:
Select the bucket you want to delete and go to "Lifecycle" under Properties.
Add a new rule Set the new rule to apply to the "Whole bucket"
Click the "Configure Rule" button in the lower right
In the "Action on Objects" pulldown, select "permanently delete"
Set the number of days to "1" You're done. The bucket will be gone in 24 hours.
Upvotes: 2
Reputation: 9318
I don't think it is possible. Not even their REST API supports deleting a non-empty bucket:
DELETE Bucket
Description
This implementation of the DELETE operation deletes the bucket named in the URI. All objects (including all object versions and Delete Markers) in the bucket must be deleted before the bucket itself can be deleted.
(taken from S3 REST API).
You are doing it the right way, by calling the delete multiple objects request. Just be aware that, if you are using versioned buckets, you must delete all objects in all of their versions before deleting the bucket.
Upvotes: 1