如何在Amazon S3存储桶中列出_all_对象?

时间:2012-03-29 07:22:43

标签: c# amazon-s3 amazon-web-services

S3Client.ListObjects仅返回1000个对象。如何使用Amazon C#库检索所有现有对象的列表?

4 个答案:

答案 0 :(得分:57)

如上所述,Amazon S3确实需要Listing Keys Using the AWS SDK for .NET

  

由于存储桶可以包含几乎无限数量的密钥,因此   列表查询的完整结果可能非常大。管理   大型结果集,Amazon S3使用分页将它们分割成   多重回复。每个列表键响应返回一页最多   带有指示符的1,000个键,指示响应是否被截断。   您发送了一系列列表键请求,直到您收到所有请求   钥匙。

上述指标是NextMarker中的ObjectsResponse Class属性 - 其用法在完整示例Listing Keys Using the AWS SDK for .NET中说明,相关片段为:

static AmazonS3 client;
client = Amazon.AWSClientFactory.CreateAmazonS3Client(
                    accessKeyID, secretAccessKeyID);

ListObjectsRequest request = new ListObjectsRequest();
request.BucketName = bucketName;
do
{
   ListObjectsResponse response = client.ListObjects(request);

   // Process response.
   // ...

   // If response is truncated, set the marker to get the next 
   // set of keys.
   if (response.IsTruncated)
   {
        request.Marker = response.NextMarker;
   }
   else
   {
        request = null;
   }
} while (request != null);

答案 1 :(得分:7)

请注意,上面的答案并未使用推荐的API来列出对象:http://docs.aws.amazon.com/AmazonS3/latest/API/v2-RESTBucketGET.html

以下代码段显示了新API的外观:

using (var s3Client = new AmazonS3Client(Amazon.RegionEndpoint.USEast1))
{
    ListObjectsV2Request request = new ListObjectsV2Request
    {
          BucketName = bucketName,
          MaxKeys = 10
    };
    ListObjectsV2Response response;
    do
    {
         response = await s3Client.ListObjectsV2Async(request);

         // Process response.
         // ...

         request.ContinuationToken = response.NextContinuationToken;

    } while (response.IsTruncated);        
}

答案 2 :(得分:0)

根据文档,客户在您描述的情况下使用分页。根据文档,您应该在结果上使用IsTruncated ...如果true再次通过正确设置Marker再次呼叫ListObjects以获取下一页等。 - 停止呼叫当IsTruncated返回false时。

答案 3 :(得分:0)

API版本已更改;因此需要执行以下操作:

            ListObjectsV2Request request = new ListObjectsV2Request
            {
                BucketName = bucketName,
                MaxKeys = 10
            };
            ListObjectsV2Response response;
            do
            {
                response = await client.ListObjectsV2Async(request);

                // Process the response.
                foreach (S3Object entry in response.S3Objects)
                {
                    Console.WriteLine("key = {0} size = {1}",
                        entry.Key, entry.Size);
                }
                Console.WriteLine("Next Continuation Token: {0}", response.NextContinuationToken);
                request.ContinuationToken = response.NextContinuationToken;
            } while (response.IsTruncated);

有关详细信息,请参见https://docs.aws.amazon.com/AmazonS3/latest/dev/ListingObjectKeysUsingNetSDK.html