본문 바로가기
C#

18# C#에서 아마존 S3 다운로드 하는법

by NaHyungMin 2019. 4. 3.

예전에 회사에서 무슨 일이 있어서 대규모 파일 비교를 해야 하는 일이 있었는데

오랜만에 Winform으로 작업해서 줘봤음. 쓰고 버릴 코드라 이름이랑 다 대충한게 문제 -.-

 

Nuget 참조.

 

using System;

using System.IO;

using System.Threading;

using System.Windows.Forms;

using Amazon;

using Amazon.S3;

using Amazon.S3.IO;

using Amazon.S3.Model;

 

namespace S3_Download

{

    public partial class Form1 : Form

    {

        AmazonS3AllDownLoader downloader = new AmazonS3AllDownLoader();

        string folderPath = "";

 

        public Form1()

        {

            InitializeComponent();

        }

 

        private void btn_start_Click(object sender, EventArgs e)

        {

            if (folderPath.Length == 0)

            {

                MessageBox.Show("폴더 선택");

                return;

            }

 

            Form1 form1 = this;

            downloader.Start(folderPath, ref form1, ref richTextBox1);

        }

 

        private void btnFileDown_Click(object sender, EventArgs e)

        {

            DialogResult result = folderBrowserDialog1.ShowDialog();

 

            if (result == DialogResult.OK)

            {

                folderPath = folderBrowserDialog1.SelectedPath;

            }

        }

    }

 

    public class AmazonS3AllDownLoader

    {

        private const string bucketName = "버킷경로";

        private const string accessKey = "accessKey ";

        private const string secretKey = "secretKey";

        private const string rootPath = "root";

        private RichTextBox text;

        delegate void StringArgReturningVoidDelegate(string text);

        Form1 fom1;

        string folderPath;

        AmazonS3Client s3Client;

 

        public void Start(string folderPath, ref Form1 form1, ref RichTextBox text)

        {

            this.folderPath = folderPath;

            this.fom1 = form1;

            this.text = text;

 

            Thread downThread = new Thread(new ThreadStart(DirectoryInfo));

            downThread.Start();

        }

 

        private void DirectoryInfo()

        {

            AmazonS3Config cfg = new AmazonS3Config

            {

                RegionEndpoint = RegionEndpoint.APNortheast1 //Tokyo

            };

 

            s3Client = new AmazonS3Client(accessKey, secretKey, cfg);

            S3DirectoryInfo dir = new S3DirectoryInfo(s3Client, bucketName, rootPath);

 

            DirSearch(dir);

        }

 

        private void DirSearch(S3DirectoryInfo s3DirectoryInfo)

        {

            try

            {

                S3FileInfo[] s3FileInfos = s3DirectoryInfo.GetFiles();

 

                //파일을 먼저 생성해주고

                foreach (S3FileInfo s3FileInfo in s3FileInfos)

                {

                    string key = s3FileInfo.DirectoryName.Replace("mb-jp-resource.owlogueservice2.com:\\"""+ s3FileInfo.Name;

                    //파일 다운로드..

                    GetObjectRequest request = new GetObjectRequest

                    {

                        BucketName = bucketName,

                        Key = key.Replace(@"\", "/"),

                    };

 

                    string filePath = s3FileInfo.Directory.FullName.Replace(s3FileInfo.Directory.Bucket.FullName, folderPath);

                    GetObjectResponse response = s3Client.GetObject(request);

 

                    response.WriteResponseStreamToFile(string.Format("{0}\\{1}", filePath, s3FileInfo.Name));

                    SetText(string.Format("{0}", s3FileInfo.Name));

                }

 

                //디렉토리를 만든다. 그러다가 디렉토리에 또 파일이 있으면? 만들어 주겠지..

                foreach (S3DirectoryInfo directory in s3DirectoryInfo.GetDirectories())

                {

                    string fullPath = directory.FullName.Replace(directory.Bucket.FullName, folderPath);

                    if (Directory.Exists(fullPath) == false)

                    {

                        Directory.CreateDirectory(fullPath);

                    }

 

                    DirSearch(directory);

                }

            }

            catch (Exception ex)

            {

                Console.WriteLine(ex.Message);

            }

        }

 

        private void SetText(string text)

        {

            if (this.text.InvokeRequired)

            {

                StringArgReturningVoidDelegate d = new StringArgReturningVoidDelegate(SetText);

                fom1.Invoke(d, new object[] { text });

            }

            else

            {

                this.text.Text += string.Format("{0}{1}", text, Environment.NewLine);

            }

        }

    }

}