재우니의 블로그

 

 

PC 내에 존재하는 폴더들을 전부 AWS S3 에 업로로 하고자 합니다. 

 

"D:\\SourceCode\\Console\\AWSS3Folder\\AWSS3Folder\\dbbackup" 경로 하단에 shimfolder 폴더가 존재합니다. 해당 폴더 하위에 폴더들이 존재하며, 또 그 하위 폴더들을 가지고 있는 구조입니다. 

 

dir.GetFiles("*", SearchOption.AllDirectories) 함수를 통해 하위폴더와 파일까지 전부 가져옵니다. 그 다음에 이를 foreach 문을 통해 aws s3 지정된 폴더로 복사 합니다.

 

 

폴더 및 파일을 업로드하기 전에 각 개별 파일을 검사하여 S3에 아직 존재하지 않는 파일만 업로드합니다. 업로드하기 전에 모든 파일의 존재 여부를 확인하면 각 파일에 대한 추가 요청이 추가되므로 모든 파일을 한 번에 업로드하는 것보다 속도가 느려질 수 있다는 점에 유의하세요. 

 

 

존 파일을 덮어쓰는 것이 허용되고 속도가 문제가 되는 경우 이 확인을 건너뛰는 것이 더 효율적일 수 있습니다.

 

 

using Amazon;
using Amazon.S3;
using Amazon.S3.Transfer;
using System.IO;
using System.Numerics;
using System.Threading.Tasks;

public class UploadDirectory
{
    private static readonly string accessKey = "your-access-key"; // AWS IAM에서 발급받은 access key
    private static readonly string secretKey = "your-secret-key"; // AWS IAM에서 발급받은 secret key


    private const string bucketName = "버킷명"; // S3 버킷명
    private const string directoryPath = "D:\\SourceCode\\Console\\AWSS3Folder\\AWSS3Folder\\dbbackup"; // 로컬 PC 폴더경로
    private static readonly RegionEndpoint bucketRegion = RegionEndpoint.APNortheast2; // 서울로 리전

    private static IAmazonS3 s3Client;

    public static void Main()
    {
        s3Client = new AmazonS3Client(accessKey, secretKey, bucketRegion);
        UploadDirAsync().Wait();
    }

    private static async Task UploadDirAsync()
    {
        try
        {
            var directoryTransferUtility =
                new TransferUtility(s3Client);

            DirectoryInfo dir = new DirectoryInfo(directoryPath);
            foreach (var fileInfo in dir.GetFiles("*", SearchOption.AllDirectories))
            {
                string key = fileInfo.FullName.Substring(directoryPath.Length + 1).Replace("\\", "/");
                // key is the relative path in S3, replace "\\" with "/" for correct folder structure

                try
                {
                    await s3Client.GetObjectMetadataAsync(bucketName, key);
                    Console.WriteLine($"File {key} already exists.");
                }
                catch (AmazonS3Exception ex)
                {
                    if (ex.StatusCode == System.Net.HttpStatusCode.NotFound)
                    {
                        await directoryTransferUtility.UploadAsync(fileInfo.FullName, bucketName, key);
                        Console.WriteLine($"Uploaded {key}");
                    }
                    else
                    {
                        throw;
                    }
                }
            }

            Console.WriteLine("Upload completed");

        }
        catch (AmazonS3Exception e)
        {
            Console.WriteLine("Error encountered on server. Message:'{0}' when writing an object", e.Message);
        }
        catch (Exception e)
        {
            Console.WriteLine("Unknown encountered on server. Message:'{0}' when writing an object", e.Message);
        }
    }
}

 

 

Program.cs
0.00MB

 

참고사이트

 

https://docs.aws.amazon.com/AmazonS3/latest/userguide/example_s3_UploadDirectoryToBucket_section.html

 

Recursively upload a local directory to an Amazon Simple Storage Service (Amazon S3) bucket - Amazon Simple Storage Service

Thanks for letting us know this page needs work. We're sorry we let you down. If you've got a moment, please tell us how we can make the documentation better.

docs.aws.amazon.com

 

 

JAVA 언어 : Recursively upload a local directory to an Amazon Simple Storage Service (Amazon S3) bucket

https://docs.aws.amazon.com/AmazonS3/latest/userguide/example_s3_UploadDirectoryToBucket_section.html

 

Recursively upload a local directory to an Amazon Simple Storage Service (Amazon S3) bucket - Amazon Simple Storage Service

Thanks for letting us know this page needs work. We're sorry we let you down. If you've got a moment, please tell us how we can make the documentation better.

docs.aws.amazon.com