Amazon Simple Storage Service
Developer Guide (API Version 2006-03-01)
« PreviousNext »
View the PDF for this guide.Go to the AWS Discussion Forum for this product.Go to the Kindle Store to download this guide in Kindle format.Did this page help you?  Yes | No |  Tell us about it...

Listing Keys Using the AWS SDK for .NET

The following tasks guide you through using the .NET classes to list object keys in a bucket.

Listing Object Keys

1

Create an instance of the AmazonS3 class by providing your AWS credentials.

2

Execute one of the AmazonS3.ListObjects. You need to provide the bucket name to list the keys. You can also specify optional information, such as retrieving keys starting with a specific prefix, and limiting result set to a specific number of keys. By default, the result set returns up to 1,000 keys. You provide this information by creating an instance of the ListObjectsRequest class.

3

Process the ListObjectResponse by iterating over the ListObjectResponse.S3Objects collection. You should check to see if the result was truncated. If yes, you send a request for the next set of keys by setting the ListObjectRequest.Marker value to the NextMarker value received in the previous response.


The following C# code sample demonstrates the preceding tasks.

static AmazonS3 client;
client = Amazon.AWSClientFactory.CreateAmazonS3Client(
                    accessKeyID, secretAccessKeyID);
                
ListObjectsRequest request = new ListObjectsRequest();
request = new ListObjectsRequest();
request.BucketName = bucketName;
request.WithPrefix("m");
request.MaxKeys = 2;
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);

Example

The following C# code example lists keys in the specified bucket. The example illustrates the use of AmazonS3.ListObjects method. It also illustrates how you can specify options to list keys, such as listing keys with a specific prefix, listing keys that start after a specific marker, and listing only a specific number of keys. For instructions on how to create and test a working sample, see Testing the .NET Code Examples

using System;
using System.Configuration;
using System.Collections.Specialized;
using Amazon.S3;
using Amazon.S3.Model;

namespace s3.amazon.com.docsamples.listingkeys
{
    class S3Sample
    {
        static string bucketName = "*** Provide bucket name ***";
        static AmazonS3 client;

        public static void Main(string[] args)
        {
            if (checkRequiredFields())
            {
                NameValueCollection appConfig =
                    ConfigurationManager.AppSettings;

                string accessKeyID = appConfig["AWSAccessKey"];
                string secretAccessKeyID = appConfig["AWSSecretKey"];

                using (client = Amazon.AWSClientFactory.CreateAmazonS3Client(
                    accessKeyID, secretAccessKeyID))
                {
                   Console.WriteLine("Listing objects stored in a bucket");
                    ListingObjects();
                }
            }

            Console.WriteLine("Press any key to continue...");
            Console.ReadKey();
        }

        static void ListingObjects()
        {
            try
            {
                ListObjectsRequest request = new ListObjectsRequest();
                request = new ListObjectsRequest();
                request.BucketName = bucketName;
                request.WithPrefix("m");
                request.MaxKeys = 2;

               do
               {
                   ListObjectsResponse response = client.ListObjects(request);

                   // Process response.
                   foreach (S3Object entry in response.S3Objects)
                   {
                       Console.WriteLine("key = {0} size = {1}",
                           entry.Key, entry.Size);
                   }

                   // 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);
            }
            catch (AmazonS3Exception amazonS3Exception)
            {
                if (amazonS3Exception.ErrorCode != null &&
                    (amazonS3Exception.ErrorCode.Equals("InvalidAccessKeyId")
                    ||
                    amazonS3Exception.ErrorCode.Equals("InvalidSecurity")))
                {
                    Console.WriteLine("Check the provided AWS Credentials.");
                    Console.WriteLine(
                    "To sign up for service, go to http://aws.amazon.com/s3");
                }
                else
                {
                    Console.WriteLine(
                     "Error occurred. Message:'{0}' when listing objects",
                     amazonS3Exception.Message);
                }
            }
        }

        static bool checkRequiredFields()
        {
            NameValueCollection appConfig = ConfigurationManager.AppSettings;

            if (string.IsNullOrEmpty(appConfig["AWSAccessKey"]))
            {
                Console.WriteLine(
                    "AWSAccessKey was not set in the App.config file.");
                return false;
            }
            if (string.IsNullOrEmpty(appConfig["AWSSecretKey"]))
            {
                Console.WriteLine(
                    "AWSSecretKey was not set in the App.config file.");
                return false;
            }
            if (string.IsNullOrEmpty(bucketName))
            {
                Console.WriteLine("The variable bucketName is not set.");
                return false;
            }

            return true;
        }
    }
}