JJC's 테크니컬 다이어리

C# SFTP 활용하기 본문

CSharp.Net

C# SFTP 활용하기

털털한JJC 2021. 3. 25. 16:38

취약한 FTP 프로토콜의 대안으로 SFTP를 사용할 수 있습니다.

C# 에서 SFTP를 구현하기 위하여 SSH.NET 을 많이 사용합니다.

Visual Studio에서 NuGet 패키지 관리자를 이용하여 라이브러리를 설치할 수 있습니다.

 

아래는 라이브러리 사용 샘플 코드 입니다.

하위폴더를 포함한 폴더를 업로드 다운로드 하는 샘플 입니다.

 

using Renci.SshNet;
using Renci.SshNet.Sftp;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace SFtpFileTransfer
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            var localDir = "D:/temp";
            var remoteDir = "/home/user";

            var files = new List<String>();
            using (SftpClient client = new SftpClient("192.168.1.3", 22, "root", "p@ssw0rd"))
            {
                client.KeepAliveInterval = TimeSpan.FromSeconds(60);
                client.ConnectionInfo.Timeout = TimeSpan.FromMinutes(180);
                client.OperationTimeout = TimeSpan.FromMinutes(180);
                client.Connect();
                bool connected = client.IsConnected;
                client.ChangeDirectory(remoteDir);
                textBox1.Text = client.WorkingDirectory;
                DownloadDirectory(client, remoteDir, localDir );
                client.Disconnect();
                System.Environment.Exit(0);
            }

        }

        private void button2_Click(object sender, EventArgs e)
        {
            var localDir = "D:/temp";
            var remoteDir = "/home/user";

            var files = new List<String>();
            using (SftpClient client = new SftpClient("192.168.1.3", 22, "root", "p@ssw0rd"))
            {
                client.KeepAliveInterval = TimeSpan.FromSeconds(60);
                client.ConnectionInfo.Timeout = TimeSpan.FromMinutes(180);
                client.OperationTimeout = TimeSpan.FromMinutes(180);
                client.Connect();
                bool connected = client.IsConnected;

                client.ChangeDirectory(remoteDir);
                textBox1.Text = client.WorkingDirectory;
                
                UploadDirectory(client, localDir, remoteDir);

                client.Disconnect();
            }

        }

        public static void DownloadDirectory(SftpClient client, string remotePath, string localPath)
        {
            Directory.CreateDirectory(localPath);
            IEnumerable<SftpFile> files = client.ListDirectory(remotePath);
            foreach (SftpFile file in files)
            {
                if ((file.Name != ".") && (file.Name != ".."))
                {
                    string sourceFilePath = remotePath + "/" + file.Name;
                    string destFilePath = Path.Combine(localPath, file.Name);
                    if (file.IsDirectory)
                    {
                        DownloadDirectory(client, sourceFilePath, destFilePath);
                    }
                    else
                    {
                        using (Stream fileStream = File.Create(destFilePath))
                        {
                            client.DownloadFile(sourceFilePath, fileStream);
                        }
                    }
                }
            }
        }
        public static void UploadDirectory(SftpClient client, string localPath, string remotePath)
        {
            Console.WriteLine("Uploading directory {0} to {1}", localPath, remotePath);

            IEnumerable<FileSystemInfo> infos =
                new DirectoryInfo(localPath).EnumerateFileSystemInfos();
            foreach (FileSystemInfo info in infos)
            {
                if (info.Attributes.HasFlag(FileAttributes.Directory))
                {
                    string subPath = remotePath + "/" + info.Name;
                    if (!client.Exists(subPath))
                    {
                        client.CreateDirectory(subPath);
                    }
                    UploadDirectory(client, info.FullName, remotePath + "/" + info.Name);
                }
                else
                {
                    using (Stream fileStream = new FileStream(info.FullName, FileMode.Open))
                    {
                        Console.WriteLine(
                            "Uploading {0} ({1:N0} bytes)",
                            info.FullName, ((FileInfo)info).Length);

                        client.UploadFile(fileStream, remotePath + "/" + info.Name);
                    }
                }
            }
        }
    }

}