Create Amazon S3 Bucket if does not exist C#
- Qayyum
- July 13, 2018
- 15,188
To create Amazon S3 bucket i used nugget package which you can install by running following nugget command in Visual Studio.
Install-Package AWSSDK.S3 -Version 3.3.19
The code part:
public class s3
{
AmazonS3Client client;
<em>
string accessKey = Properties.Settings.Default.s3AccessKey;
string secretKey = Properties.Settings.Default.s3SecretKey;
string bucket = Properties.Settings.Default.s3Bucket;
</em>
public async Task<int> CreateBucket()
{
try
{
using (client = new AmazonS3Client(accessKey, secretKey, Amazon.RegionEndpoint.USEast1))
{
bool bucketExist = false;
S3DirectoryInfo root = new S3DirectoryInfo(client, "");
Console.WriteLine(accessKey);
Console.WriteLine(secretKey);
Console.WriteLine(bucket);
foreach (S3DirectoryInfo subDirectory in root.GetDirectories())
{
if (subDirectory.Name == bucket)
{
Console.WriteLine(subDirectory.Name);
bucketExist = true;
return 1;
}
}
if (!bucketExist)
{
root.CreateSubdirectory(bucket);
return 2;
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
return 0;
}
}
How to use:
s3 s = new s3();
int response = await s.CreateBucket();
switch (response)
{
case 1:
lblCreateBucketStatus.Text = "Bucket already exists, try new name.";
lblCreateBucketStatus.ForeColor = Color.Orange;
break;
case 2:
lblCreateBucketStatus.Text = "Bucket created.";
lblCreateBucketStatus.ForeColor = Color.Green;
break;
case 0:
lblCreateBucketStatus.Text = "Failed, Please try again (maybe different bucket name).\nBucket name should be lowercase, no spaces.";
lblCreateBucketStatus.ForeColor = Color.Red;
MessageBox.Show("");
break;
default:
break;
}