새소식

카테고리 없음

C# SFTP Folder Upload

  • -
728x90

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);
                    }
                }
            }
        }
반응형
Contents

포스팅 주소를 복사했습니다

이 글이 도움이 되었다면 공감 부탁드립니다.