How can I non-recursively browse the contents of a directory with the AWS S3 API?

后端 未结 1 1758
野性不改
野性不改 2021-02-01 23:01

Say I have the following directories and files in an Amazon S3 bucket (files are in bold):

  • bucketname/
  • bucketname/folder1/
  • bucke
相关标签:
1条回答
  • 2021-02-01 23:25

    I had the opposite problem (I knew how to get the files in the specified folder, but not the subdirectories).

    The answer is that Amazon lists files differently than it does sub-folders.

    Sub-folders are listed, as your example shows, in the ListObjectsResponse.CommonPrefixes collection.

    Files are listed in the ListObjectsResponse.S3Objects collection.

    So your code should look like this:

    var request = new ListObjectsRequest()
    .WithBucketName("bucketname")
    .WithPrefix(@"folder1/")
    .WithDelimiter(@"/");
    
    using (var client = Amazon.AWSClientFactory.CreateAmazonS3Client(accessKey, secretKey))
    using (var response = client.ListObjects(request))
    {
        foreach (var subFolder in response.CommonPrefixes)
        {
            /* list the sub-folders */
        }
        foreach (var file in response.S3Objects) {
             /* list the files */
        }
    }
    

    my google search turned up this post on the burningmonk blog with this in the comment section:

    When you make the Lis­tO­b­jects request, to list the top level fold­ers, don’t set the pre­fix but set the delim­iter to ‘/’, then inspect the ‘Com­mon­Pre­fixes’ prop­erty on the response for the fold­ers that are in the top folder.

    To list the con­tents of a ‘root­folder’, make the request with pre­fix set to the name of the folder plus the back­slash, e.g. ‘rootfolder/’ and set the delim­iter to ‘/’. In the response you’ll always have the folder itself as an ele­ment with the same key as the pre­fix you used in the request, plus any sub­fold­ers in the ‘Com­mon­Pre­fixes’ property.

    0 讨论(0)
提交回复
热议问题