public void TestCleanup() { try { var objRequest = new ListObjectsRequest() { BucketName = this.bucketName }; using (var objResponse = client.ListObjects(objRequest)) { var delRequest = new DeleteObjectsRequest() { BucketName = this.bucketName, Quiet = true }; delRequest.AddKeys(objResponse.S3Objects.Select(o => new KeyVersion(o.Key)).ToArray()); using (var delResponse = client.DeleteObjects(delRequest)) { } } var deleteRequest = new DeleteBucketRequest() { BucketName = this.bucketName }; using (var deleteResponse = client.DeleteBucket(deleteRequest)) { } } catch (Exception ex) { this.TestContext.WriteLine("Warning: Could not cleanup bucket: {0}. {1}", this.bucketName, ex); } }
/// <summary> /// Deletes all keys in a given bucket, then deletes the bucket itself. /// </summary> /// <param name="client">The client to use.</param> /// <param name="bucketName">The bucket to delete.</param> public static void DeleteBucketRecursive(this AmazonS3 client, string bucketName) { while(true) { // attempt to delete the bucket try { var deleteRequest = new DeleteBucketRequest() { BucketName = bucketName }; using (var deleteResponse = client.DeleteBucket(deleteRequest)) { // deletion was successful return; } } catch (AmazonS3Exception ex) { if (ex.ErrorCode != "BucketNotEmpty") throw ex; } var objRequest = new ListObjectsRequest() { BucketName = bucketName }; using (var objResponse = client.ListObjects(objRequest)) { var delRequest = new DeleteObjectsRequest() { BucketName = bucketName, Quiet = true }; // select the objects to delete (up to the supported limit of 1000) var objToDelete = objResponse.S3Objects.Take(1000).Select(o => new KeyVersion(o.Key)); delRequest.AddKeys(objToDelete.ToArray()); using (var delResponse = client.DeleteObjects(delRequest)) { } } } }