관리 메뉴

팀드모네 IT Blog

C# SFTP Folder Upload 본문

카테고리 없음

C# SFTP Folder Upload

남명 팀드모네 2021. 7. 20. 10:48

Good luck to you! bro

public static bool SftpUpload(string localDir, string remoteDir, bool blMakeDir = true)
        {
            if (string.IsNullOrEmpty(remoteDir))
            {
                MessageBoxEx.Show("Upload path is not specified");
                return false;
            }

            try
            {
                using (SftpClient client = new SftpClient("192.168.0.1", 22, "user", "password"))
                {
                    client.KeepAliveInterval = TimeSpan.FromSeconds(60);
                    client.ConnectionInfo.Timeout = TimeSpan.FromMinutes(180);
                    client.OperationTimeout = TimeSpan.FromMinutes(180);
                    client.Connect();
                    if (client.IsConnected)
                    {
                        if (!client.Exists(remoteDir))
                        {
                            client.CreateDirectory(remoteDir);
                        }
                        client.ChangeDirectory(remoteDir);
                        UploadDirectory(client, localDir, remoteDir);
                    }
                    else
                    {
                        MessageBoxEx.Show("SFTP server connection failed.");
                        return false;
                    }
                    client.Disconnect();
                }
            }
            catch(Exception e)
            {
                MessageBoxEx.Show(e);
                return false;
            }
            return true;
        }

        public static void UploadDirectory(SftpClient client, string localPath, string 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);
                    }
                }
            }
        }
0 Comments
댓글쓰기 폼