Server/File Server

[FTP] Console FTP 예제 프로그램

DungDung.dev 2023. 12. 11. 17:47

 

https://dungdung-developer.tistory.com/7

 

[FTP] Windows IIS FTP 사이트 및 사용자, 네트워크 설정

어쩌다 보니 IIS FTP 사이트를 구축할 일이 생겨서 예전에 사용해 봤습니다. 토이 프로젝트를 하시는 분들이나 혹시 언젠가 도움이 될까 싶어 간단하게 FTP 사이트를 설정한 과정을 정리해보았습

dungdung-developer.tistory.com

 

 

 

간단하게 FRP 서버에 연결하는 console 프로그램을  게시글로 공유해봅니다. 코드 첨부파일은 하단에 있습니다.

 

 

 

파일의 구조는 아래와 같습니다.

  • 솔루션 이름 : FTP_Test1
    • 세팅 파일 : appsettings.json
    • Lazy Singleton : LocalVar.cs
    • Interface : IFTPtransaction
    • 구현 : FTPtransaction.cs
    • Manager : FTPManager.cs
    • Program.cs

 

  • appsettings.json
{
  "ConnectionData": {
    "addr": "127.0.0.1",
    "user": "user",
    "pwd": "password",
    "port": "5400"
  },

  "Url": {
    //업로드 할 파일 저장할 FTP 경로 지정
    "Server_Upload": "\\UpLoadTest\\",
    //업로드 할 Local 경로
    "Local_Upload": "C:\\FTP_TestFolder\\UpLoadTest",

    //다운로드 받을 FTP 상세 경로
    "Server_Download": "DownlodeTest\\index.txt",
    //FTP에서 다운 받은 파일을 저장할 Local 경로 설정
    "Local_Download": "C:\\FTP_TestFolder\\DownlodeTest\\test.txt"
  }
}

 

  • LocalVar.cs
    using Microsoft.Extensions.Configuration;
    using System;
    using System.IO;
    
    namespace FTP_Test1
    {
        public class LocalVar
        {
            private static readonly Lazy<LocalVar> _local = new Lazy<LocalVar>(() => new LocalVar());
    
            public readonly string addr = string.Empty;
            public readonly string user = string.Empty;
            public readonly string pwd = string.Empty;
            public readonly string port = string.Empty;
    
            public readonly string Server_Upload = string.Empty;
            public readonly string Local_Upload = string.Empty;
    
            public readonly string Server_Download = string.Empty;
            public readonly string Local_Download = string.Empty;
            /// <summary>
            ///  생성자
            /// </summary>
            public static LocalVar Variable { get { return _local.Value; } }
    
            private LocalVar()
            {
                addr = JsonConfigurationString("ConnectionData:addr").Value;
                user = JsonConfigurationString("ConnectionData:user").Value;
                pwd = JsonConfigurationString("ConnectionData:pwd").Value;
                port = JsonConfigurationString("ConnectionData:port").Value;
    
                Server_Upload = JsonConfigurationString("Url:Server_Upload").Value;
                Local_Upload = JsonConfigurationString("Url:Local_Upload").Value;
    
                Server_Download = JsonConfigurationString("Url:Server_Download").Value;
                Local_Download = JsonConfigurationString("Url:Local_Download").Value;
            }
    
            private IConfigurationSection JsonConfigurationString(string strigName)
            {
                IConfigurationRoot root = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory()).AddJsonFile("appsettings.json", optional: false).Build();
                IConfigurationSection section = root.GetSection(strigName);
                return section;
            }
        }
    }

 

  • IFTPtransaction
    using System;
    using System.Collections.Generic;
    using System.Text;
    
    namespace FTP_Test1
    {
        public interface IFTPtransaction
        {
            bool Connection(out string ErrMessage);
    
            bool FileUpload(string filename, out string ErrMessage);
    
            bool FileDownload(out string ErrMessage);
    
            bool DeleteFile(string fileName, out string ErrMessage);
    
            List<string> GetFileList(string serverFolder);
        }
    }

 

  • FTPtransaction.cs
    using System;
    using System.IO;
    
    namespace FTP_Test1
    {
        class FTPManager
        {
            readonly IFTPtransaction iFTPtransaction = new FTPtransaction();
    
            public void Connection()
            {  
                // 서버 접속
                if (iFTPtransaction.Connection(out string ConErrMessage) == true)
                {
                    Console.WriteLine("FTP 접속 성공");
                }
                else
                {
                    Console.WriteLine("FTP 접속 실패");
                    Console.WriteLine(ConErrMessage);
                }
            }
    
            public void Upload()
            {
                DirectoryInfo dirInfo = new DirectoryInfo(LocalVar.Variable.Local_Upload);
                //FileInfo[] infos = dirInfo.GetFiles();
                // 업로드
                foreach (FileInfo info in dirInfo.GetFiles())
                {
                    if (iFTPtransaction.FileUpload(info.FullName, out string UpErrMessage) == true)
                        Console.WriteLine("FTP Upload Success!");
                    else
                    {
                        Console.WriteLine("FTP Upload Fail!");
                        Console.WriteLine(UpErrMessage);
                    }
                }
            }
    
            public void Download()
            {
                // 다운로드
                if (iFTPtransaction.FileDownload(out string DownErrMessage) == true)
                    Console.WriteLine("Download Success!");
                else
                {
                    Console.WriteLine("Download Fail!");
                    Console.WriteLine(DownErrMessage);
                }
            }
    
            public void Delete(string fileName)
            {
                // 삭제
                if (iFTPtransaction.DeleteFile(fileName, out string DelErrMessage) == false)
                {
                    Console.WriteLine("FTP Delete Fail!");
                    Console.WriteLine(DelErrMessage);
                }
                else
                    Console.WriteLine("FTP Delete Success!");
            }
        }
    }

 

  • FTPManager.cs
    using System;
    using System.IO;
    
    namespace FTP_Test1
    {
        class FTPManager
        {
            readonly IFTPtransaction iFTPtransaction = new FTPtransaction();
    
            public void Connection()
            {  
                // 서버 접속
                if (iFTPtransaction.Connection(out string ConErrMessage) == true)
                {
                    Console.WriteLine("FTP 접속 성공");
                }
                else
                {
                    Console.WriteLine("FTP 접속 실패");
                    Console.WriteLine(ConErrMessage);
                }
            }
    
            public void Upload()
            {
                DirectoryInfo dirInfo = new DirectoryInfo(LocalVar.Variable.Local_Upload);
                //FileInfo[] infos = dirInfo.GetFiles();
                // 업로드
                foreach (FileInfo info in dirInfo.GetFiles())
                {
                    if (iFTPtransaction.FileUpload(info.FullName, out string UpErrMessage) == true)
                        Console.WriteLine("FTP Upload Success!");
                    else
                    {
                        Console.WriteLine("FTP Upload Fail!");
                        Console.WriteLine(UpErrMessage);
                    }
                }
            }
    
            public void Download()
            {
                // 다운로드
                if (iFTPtransaction.FileDownload(out string DownErrMessage) == true)
                    Console.WriteLine("Download Success!");
                else
                {
                    Console.WriteLine("Download Fail!");
                    Console.WriteLine(DownErrMessage);
                }
            }
    
            public void Delete(string fileName)
            {
                // 삭제
                if (iFTPtransaction.DeleteFile(fileName, out string DelErrMessage) == false)
                {
                    Console.WriteLine("FTP Delete Fail!");
                    Console.WriteLine(DelErrMessage);
                }
                else
                    Console.WriteLine("FTP Delete Success!");
            }
        }
    }

 

  • Program.cs
using System;

namespace FTP_Test1
{
    class Program
    {
        static void Main()
        {
            var manager = new FTPManager();
            manager.Connection();
            manager.Upload();
            manager.Download();

            Console.Write("파일 이름 입력 : ");
            string filename = Console.ReadLine();
            manager.Delete(filename);
        }
    }
}

 

 

 

  • 아래와 같이 ASP.NET Core Web API (.NET 6.0)을 이용해서 구현한 예제도 있으니 필요하시면 다운받아주세요.

 

 

 

 

FTP_Test_Console-main.zip
0.57MB
IISFTP_TestAPI-master.zip
0.01MB

 

 

 

 

 

 

 

 

 

 첫 회사에 입사하고 '무언가 해봐야겠다!'는 의지로 구현한 코드라서 알 수 없는 의지들이 곳곳에 보이네요. 지금은 사용하지 않는 기술이기에 나중에 기회가 된다면 다시 구현해보고 싶습니다.

 

부족하거나 질문사항이 있다면 언제나 코멘트 남겨주세요! 감사합니다.