Jesus is Lord
Jesus is Lord

Reputation: 15409

How do I get the top-level directories of a bucket in S3?

How do I list of the common prefixes for the objects in my bucket?

If I use ListObjects, I am able to retrieve objects. I can see there's a common prefix called 2017:

using (var client = new AmazonS3Client())
{
    var listObjectsResponse = client.ListObjects(new ListObjectsRequest
    {
        BucketName = bucket,
        Prefix = "2",
        Delimiter = "",
    });

    // Prints: 2017/11/08/<omitted>.json
    Console.WriteLine(listObjectsResponse.S3Objects.First().Key);        
}

However if I set Delimiter, nothing is returned:

using (var client = new AmazonS3Client())
{
    var listObjectsResponse = client.ListObjects(new ListObjectsRequest
    {
        BucketName = bucket,
        Prefix = "2",
        Delimiter = "/",
    });

    // Prints: 0
    Console.WriteLine(listObjectsResponse.S3Objects.Count);      
}

How do I get the common prefixes like 2017 to be returned?

I've tried looking at the documentation and it just says to use prefix and delimiter, but that's not working.

Upvotes: 1

Views: 800

Answers (1)

Jesus is Lord
Jesus is Lord

Reputation: 15409

I see there's a CommonPrefixes property on ListObjectsResponse.

using (var client = new AmazonS3Client())
{
    var listObjectsResponse = client.ListObjects(new ListObjectsRequest
    {
        BucketName = bucket,
        Prefix = "2",
        Delimiter = "/",
    });

    // Prints: 2017
    Console.WriteLine(listObjectsResponse.CommonPrefixes[0]);     
}

Upvotes: 1

Related Questions