Creating an S3 bucket

Let's follow the tradition of building a Hello World application on AWS. We will write a simple C# .NET application that creates a new S3 bucket on your AWS account.

The following are the steps to create an S3 bucket:

  1. Open Visual Studio.
  2. Go to File | New | Project and under Visual C#, select the AWS Sample Projects and choose AWS Empty Project:
  1. Provide a name for the project and click OK.
  2. You will be prompted to provide the AWS secret key and AWS secret access key. If you already have a profile created, you can select the existing profile or create a new one by entering the credentials. Click OK when done. 

You will now see two files open: App.config and Program.cs . The app.config file is the configuration file for the application, we won't be using this file for now. The Program.cs file is the actual source code of your program. 

  1. In the Program.cs file, add the following lines of code:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Collections.Specialized;
using System.Configuration;

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

namespace pactpubAWS
{
class S3Demo
{
public static void Main(string[] args)
{
createS3Bucket(); // invoke the method to create an S3 bucket

Console.ReadKey();
}

static void createS3Bucket()
{
try
{
IAmazonS3 s3Client = new AmazonS3Client();
PutBucketRequest bucket_request = new PutBucketRequest();
bucket_request.BucketName = "packt-pub";
s3Client.PutBucket(bucket_request);
}
catch (AmazonS3Exception s3exception)
{
Console.WriteLine("Error!!");
Console.WriteLine(s3exception.ErrorCode);
}

}
}
}
  1. Execute the program and it will create a new S3 bucket named packt-pub under your AWS account.
  2. If there are any errors encountered during the creation of the bucket, the error code will be displayed on the console.

In this small console application, we first included the necessary libraries from the AWS SDK. We wrote a function named createS3Bucket and created an S3 client object using the IAmazonS3 and AmazonS3Client classes. Next, we created an S3 put-request object using the PutBucketRequest class and set its object property called BucketName to packt-pub. The request is then invoked using the PutBucket() method which creates a bucket on AWS. Errors are caught in the AmazonS3Exception object and the error code is displayed on the console.

Now that we know how to create an S3 bucket programmatically, let's try to list the available buckets.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.219.135.129