Upload directory on AWS S3 bucket using C#

2.6k Views Asked by At

For each run, application (windows forms) extracts output to file (excel/.csv/.pdf), creates current date as folder name and stores it locally. Have to capture those output directly to S3 bucket, successfully uploaded each file as below.

AmazonUploader class

using System;
using System.Collections.Generic;
using System.Text;
using Amazon;
using Amazon.S3;
using Amazon.S3.Transfer;

namespace AwsS3DemoConsoleApp
{
    public class AmazonUploader
    {
        public bool sendMyFileToS3(string localFilePath, string bucketName, string subDirectoryInBucket, string fileNameInS3)
        {
SecretConsumer secretConsumer = new SecretConsumer();
            IAmazonS3 client = new AmazonS3Client(secretConsumer.AWSAccessKey, secretConsumer.AWSSecretKey, RegionEndpoint.APSouth1);
TransferUtility utility = new TransferUtility(client);
TransferUtilityUploadRequest request = new TransferUtilityUploadRequest();
            if (subDirectoryInBucket == "" || subDirectoryInBucket == null)
            {
                request.BucketName = bucketName; //no subdirectory just bucket name
            }
            else
{   // subdirectory and bucket name
                request.BucketName = bucketName + @"/" + subDirectoryInBucket;
            }
 request.Key = fileNameInS3; 
            request.FilePath = localFilePath; 
            utility.Upload(request); 
            return true;
        }
    }
}

Program class

using System;

namespace AwsS3DemoConsoleApp
{
    internal class Program
    {
        static void Main(string[] args)
        {
            string fileToBackup = @"C:\Users\marvel\Documents\Spiderman\19-05-2022"; // test file path from the local computer
            string myBucketName = "cccfilestorage"; // your s3 bucket name goes here
            string s3DirectoryName = "dummy_folder"; // the directory path to a sub folder goes here
            string s3FileName = "19-05-2022"; // the name of the file when its saved into the S3 buscket
            AmazonUploader myUploader = new AmazonUploader();
            myUploader.sendMyFileToS3(fileToBackup, myBucketName, s3DirectoryName, s3FileName);
            Console.WriteLine("File uploaded to S3");
        }
    }
}

I want to upload as a complete directory for each run.

current folder structure 19-05-2022(main directory) sub directory (1) sub directory (2) csv pdf excel

I'm sure that we can upload folders using transfer utility Can anyone please guide me how to achieve it?

0

There are 0 best solutions below