Similar to this post, here’s a LINQPad script to delete every item from an Amazon S3 bucket:

var awsAccessKeyId = "<access key id>";
var awsSecretAccessKey = "<secret access key>";

var client = new AmazonS3Client( awsAccessKeyId, awsSecretAccessKey );

var listBuckets = client.ListBuckets();
var bucket = listBuckets.Buckets.First();

List<S3Object> objects;

while ( ( objects = client.ListObjects( new ListObjectsRequest { BucketName = bucket.BucketName } ).S3Objects ).Count > 0 )
{
    "".Dump( string.Format( "Deleting {0} items from {1}", objects.Count, bucket.BucketName ) );

    try
    {
        objects.AsParallel().ForAll( o =>
        {
            o.Key.Dump();
            client.DeleteObject( new DeleteObjectRequest { BucketName = bucket.BucketName, Key = o.Key } );
        } );
    }
    catch ( Exception ex )
    {
        // Don't care... just keep going :)
    }
}

Some things you’ll need:

  • Values for awsAccessKeyId and awsSecretAccessKey
  • A proper filter to get the appropriate bucket.  This example just gets the first bucket and wipes it, so use with care :)
  • The AWS SDK for .NET from here (either let it install to the GAC or add a reference from LINQPad).
  • LINQPad, or to use outside of LINQPad just remove the calls to Dump().
DotNetKicks Image
About these ads