프로그래밍/C#

[C#] FTP 연결

Victory_HA 2023. 3. 17. 14:26
  • EnterpriseDT.Net.Ftp를 이용한 FTP 연결 코드
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Net;
using System.Threading.Tasks;
using EnterpriseDT.Net.Ftp;

public class FtpOperationExample
{
    public static void Main(string[] args)
    {
        try
        {
            var srcDirPath = @"C:\Users\seungha.lee\Desktop\minio_src";
            var dstDirPath = "/ftpcopy";
            var localDstDirPath = "/ftpcopy";
            var ftpUsername = "mlsftp";
            var ftpPassword = "mlsftp1234";

            var srcFullPath = Directory.GetFiles(srcDirPath);
            var dstFullPath = new List<string>();

            foreach (var file in srcFullPath)
            {
                var fileName = Path.GetFileName(file);
                //var tmpPath = dstDirPath + "/" + fileName;
                var tmpPath = localDstDirPath + "/" + fileName;
                dstFullPath.Add(tmpPath);

            }

            FTPConnection ftp = new FTPConnection();
            //ftp.ServerAddress = "192.168.170.25";
            ftp.ServerAddress = "127.0.0.1";
            ftp.ServerPort = 21;
            ftp.UserName = ftpUsername;
            ftp.Password = ftpPassword;
            ftp.Connect();

            //await Task.Run(() => ftp.Connect());

            if (!ftp.IsConnected)
            {
                Console.WriteLine("FTP 연결 실패");
                return;
            }

            if (!ftp.DirectoryExists(dstDirPath))
            {
                Console.WriteLine("경로 없음");
                return;
            }

            // 데이터 복사
            Stopwatch stopwatch = Stopwatch.StartNew();
            var elapsed = new List<long>();
            stopwatch.Start();

            for (int i = 0; i < srcFullPath.Length; i++)
            {
                //ftp.UploadFile(srcFullPath[i], dstFullPath[i]);
                ftp.DownloadFile(srcFullPath[i], dstFullPath[i]);
                elapsed.Add(stopwatch.ElapsedMilliseconds);
            }
            stopwatch.Stop();

            foreach (var item in elapsed)
            {
                Console.WriteLine($"{(float)item / 1000} s");
            }

            ftp.Close();
        }
        catch (Exception ex)
        {
            Console.WriteLine($"An error occurred: {ex.Message}");
        }
    }
}  

'프로그래밍 > C#' 카테고리의 다른 글

[C#] Transaction  (0) 2023.03.29
[C#] 배열에 항목 추가하기  (0) 2023.03.20
[C#] CMD 실행 후 원격PC의 tasklist 확인하기  (0) 2023.03.17
[C#] Tips and tricks  (0) 2023.02.14
[C#] 프로젝트 빌드 시 관리자권한 부여  (0) 2023.02.06