.NET C#: Upload a File to Amazon AWS S3 With .NET and C#

2/3/2015 4:18:34 PM

This code is C# .NET and can be used to upload a file on your local machine to an AWS S3 bucket.

*Requires Nuget Package "AWS SDK for .NET" (code below uses v. 2.3.18.0)

* AWS S3 Service Urls: http://docs.aws.amazon.com/general/latest/gr/rande.html#s3_region

//BEGIN TEST CODE

string accessKey = "YOUR ACCESS KEY";
string secretAccessKey = "YOUR SECRETY KEY";
string filePath = "C:\\Projects\\Testing\\Temp Files\\test.jpg";
string s3Bucket = "your.bucket.name/subdirectory-if-needed";
string serviceUrl = "http://s3-external-1.amazonaws.com";  //N. Virginia service url         
string newFileName = "test-" + DateTime.Now.Ticks.ToString() + ".jpg"; //new filename in s3, optional

//create aws object
MyUtilities.AWS.S3 s3 = new MyUtilities.AWS.S3(accessKey, secretAccessKey, serviceUrl);

//upload
s3.UploadFile(filePath, s3Bucket, newFileName, false);

//END TEST CODE


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace MyUtilities.AWS
{
    public class S3
    {        
        Amazon.S3.AmazonS3Client S3Client = null;

        public S3(string accessKeyId, string secretAccessKey, string serviceUrl)
        {            
            Amazon.S3.AmazonS3Config s3Config = new Amazon.S3.AmazonS3Config();
            s3Config.ServiceURL = serviceUrl;

            this.S3Client = new Amazon.S3.AmazonS3Client(accessKeyId, secretAccessKey, s3Config);
        }


        public void UploadFile(string filePath, string s3Bucket, string newFileName, bool deleteLocalFileOnSuccess)
        {
            //save in s3
            Amazon.S3.Model.PutObjectRequest s3PutRequest = new Amazon.S3.Model.PutObjectRequest();
            s3PutRequest = new Amazon.S3.Model.PutObjectRequest();
            s3PutRequest.FilePath = filePath;
            s3PutRequest.BucketName = s3Bucket;
            s3PutRequest.CannedACL = Amazon.S3.S3CannedACL.PublicRead;

            //key - new file name
            if (!string.IsNullOrWhiteSpace(newFileName))
            {
                s3PutRequest.Key = newFileName;
            }

            s3PutRequest.Headers.Expires = new DateTime(2020, 1, 1);

            try
            {
                Amazon.S3.Model.PutObjectResponse s3PutResponse = this.S3Client.PutObject(s3PutRequest);

                if (deleteLocalFileOnSuccess)
                {
                    //Delete local file
                    if (System.IO.File.Exists(filePath))
                    {
                        System.IO.File.Delete(filePath);
                    }
                }
            }
            catch (Exception ex)
            {
                //handle exceptions
            }
        }
    }
}