This post follows on from part 1. With the AWS S3 objects in place it is now time to create a simple C# console application that will upload a text file stored locally to the AWS S3 bucket.
The first step is to create a test file that you want to upload. In my example, I have created a text file in the Downloads folder called TheFile.txt which contains some text. After creating the text file, note the name of the file and its location.
Start Visual Studio and create a new console application
Use NuGet to add the AWSSDK.S3 package. At the time of writing this was at version 3.3.16.2
Add the following to App.config
You will find the values for the access key and secret key in the accessKeys.csv which you downloaded in part one of the tutorial.
Create a new class called S3Uploader and paste the following code ensuring you change the variables for bucketName, keyName and filePath as appropriate. As you can see from the comments, this code is based on this answer from Stack Overflow.
For the sake of brevity the code deliberately does not have any exception handling nor unit tests as I wanted this example to focus purely on the AWS API without any other distractions.
using Amazon.S3; using Amazon.S3.Model; namespace S3FileUploaderGeekOut { /// /// Based upon https://stackoverflow.com/a/41382560/55640 /// public class S3Uploader { private string bucketName = "myimportantfiles"; private string keyName = "TheFile.txt"; private string filePath = @"C:UsersIanDownloadsTheFile.txt"; public void UploadFile() { var client = new AmazonS3Client(Amazon.RegionEndpoint.EUWest2); PutObjectRequest putRequest = new PutObjectRequest { BucketName = bucketName, Key = keyName, FilePath = filePath, ContentType = "text/plain" }; PutObjectResponse response = client.PutObject(putRequest); } } }
In the Program.cs class add the following:
namespace S3FileUploaderGeekOut { class Program { static void Main(string[] args) { S3Uploader s3 = new S3Uploader(); s3.UploadFile(); } } }
Run the program and once it completes, navigate to your S3 Bucket via the AWS console and you will be able to see that your file has been successfully uploaded.
Summary
In this and the previous post I have demonstrated the steps required to upload a text file from a simple C# console application to a AWS bucket.
The Add the following to App.config section is blank. Please correct.
Thank you Ankur for this correction, I have now added the missing content from App.config
Thank you so much! This got me past this so easy!
Thank you for the nice feedback Daniel, I’m glad it helped.