User guide

namespace s3.amazon.com.docsamples.retrieveobject
{
class S3Sample
{
static string bucketName = "bucket-name";
static string keyName = "folder/file-name.txt";
static IAmazonS3 client;
public static void Main(string[] args) {
string responseBody = "";
try {
using (client = new AmazonS3Client()) {
Console.WriteLine("Retrieving (GET) an object");
GetObjectRequest request = new GetObjectRequest() {
BucketName = bucketName,
Key = keyName
};
using (GetObjectResponse response = client.GetObject(request))
using (Stream responseStream = response.ResponseStream)
using (StreamReader reader = new StreamReader(responseStream))
responseBody = reader.ReadToEnd();
}
}
using (FileStream s = new FileStream( "s3Object.txt", FileMode.Create
))
using (StreamWriter writer = new StreamWriter(s)) {
writer.WriteLine( responseBody );
}
}
catch (AmazonS3Exception s3Exception) {
Console.WriteLine(s3Exception.Message, s3Exception.InnerException);
}
} // main
} // class
} // namespace
To test the sample code
1. Open Visual Studio and create an AWS Console project.
2. Replace the code in the Program.cs file with the sample code.
3. Replace bucket-name with the name of your Amazon S3 bucket and folder/file-name.txt
with the name of a text file in the bucket.
4. Compile and run the sample program. If the program succeeds, it displays the following output and
creates a file named s3Object.txt on your local drive that contains the text it retrieved from the
text file in Amazon S3.
Retrieving (GET) an object
Version v2.0.0
109
AWS SDK for .NET Developer Guide
Tutorial: Using an IAM Role