Amazon Simple Storage Service
Developer Guide (API Version 2006-03-01)
Print this pageEmail this pageGo to the ForumsView the PDFShare this page on TwitterShare this page on FacebookBookmark this page on DeliciousSubmit this page to RedditSubmit this page to DiggDid this page help you?  Yes  No   Tell us about it...

Get an Object Using the AWS SDK for .NET

The following tasks guide you through using the .NET classes to retrieve an object or a portion of the object.

Downloading Objects

1

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

2

Execute one of the AmazonS3.GetObject methods. You need to provide information such as bucket name, file path, or a stream. You provide this information by creating an instance of the GetObjectRequest class.

3

Execute one of the GetObjectResponse.WriteResponseStreamToFile methods to save the stream to a file.


The following C# code sample demonstrates the preceding tasks.

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

GetObjectRequest request = new GetObjectRequest()
            .WithBucketName(bucketName).WithKey(keyName);
using (GetObjectResponse response = client.GetObject(request))
{
   string title = response.Metadata["x-amz-meta-title"];
   Console.WriteLine("The object's title is {0}", title);
   string dest = Path.Combine(Environment.GetFolderPath(
         Environment.SpecialFolder.Desktop), keyName);
   if (!File.Exists(dest))
   {
       response.WriteResponseStreamToFile(dest);
   }
}

Instead of reading the entire object you can read only the portion of the object data by specifying the byte range in the request, as shown in the following C# code sample.

GetObjectRequest request = new GetObjectRequest()
        .WithBucketName(bucketName)
        .WithKey(keyName)
        .WithByteRange(0, 10);

When retrieving an object, you can optionally override the response header values (see Getting Objects) by using the ResponseHeaderOverrides object and setting the corresponding request property, as shown in the following C# code sample.

GetObjectRequest request = new GetObjectRequest()
     .WithBucketName(bucketName).WithKey(keyName);

ResponseHeaderOverrides responseHeaders = new ResponseHeaderOverrides();
responseHeaders.CacheControl = "No-cache";
responseHeaders.ContentDisposition = "attachment; filename=testing.txt";

request.ResponseHeaderOverrides = responseHeaders;

Example

The following C# code example retrieves an object from an Amazon S3 bucket. From the response, the example reads the object data using the GetObjectResponse.ResponseStream property. 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 System.IO;

using Amazon.S3;
using Amazon.S3.Model;

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

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

                string accessKeyID = appConfig["AWSAccessKey"];
                string secretAccessKeyID = appConfig["AWSSecretKey"];
                try
                {
                    Console.WriteLine("Retrieving (getting) an object");
                    string data = ReadingAnObject(
                                             accessKeyID, secretAccessKeyID);
                }
                catch (AmazonS3Exception s3Exception)
                {
                    Console.WriteLine(s3Exception.Message,
                                      s3Exception.InnerException);
                }
            }

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

        static string ReadingAnObject(
                       string accessKeyID, string secretAccessKeyID)
        {
            string responseBody = "";
            using (client = Amazon.AWSClientFactory.CreateAmazonS3Client(
                                             accessKeyID, secretAccessKeyID))
            {
                GetObjectRequest request = new GetObjectRequest()
                    .WithBucketName(bucketName).WithKey(keyName);

                using (GetObjectResponse response = client.GetObject(request))
                {
                    string title = response.Metadata["x-amz-meta-title"];
                    Console.WriteLine("The object's title is {0}", title);

                    using (Stream responseStream = response.ResponseStream)
                    {
                        using (StreamReader reader =
                            new StreamReader(responseStream))
                        {
                            responseBody = reader.ReadToEnd();
                        }
                    }
                }
            }
            return responseBody;
        }

        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;
            }
            if (string.IsNullOrEmpty(keyName))
            {
                Console.WriteLine("The variable keyName is not set.");
                return false;
            }

            return true;
        }
    }
}