Downloading a directory using SSH.NET SFTP in C#

前端 未结 1 1356
暖寄归人
暖寄归人 2021-01-03 00:47

I am using Renci.SSH and C# to connect to my Unix server from a Windows machine. My code works as expected when the directory contents are only files, but if the directory

相关标签:
1条回答
  • 2021-01-03 01:27

    BeginDownloadFile downloads a file. You cannot use it to download a folder. For that you need to download contained files one by one.

    The following example uses synchronous download (DownloadFile instead of BeginDownloadFile) for simplicity. After all, you are synchronously waiting for asynchronous download to complete anyway. To implement a progress bar with synchronous download, see Displaying progress of file download in a ProgressBar with SSH.NET.

    public static void DownloadDirectory(
        SftpClient sftpClient, string sourceRemotePath, string destLocalPath)
    {
        Directory.CreateDirectory(destLocalPath);
        IEnumerable<SftpFile> files = sftpClient.ListDirectory(sourceRemotePath);
        foreach (SftpFile file in files)
        {
            if ((file.Name != ".") && (file.Name != ".."))
            {
                string sourceFilePath = sourceRemotePath + "/" + file.Name;
                string destFilePath = Path.Combine(destLocalPath, file.Name);
                if (file.IsDirectory)
                {
                    DownloadDirectory(sftpClient, sourceFilePath, destFilePath);
                }
                else
                {
                    using (Stream fileStream = File.Create(destFilePath))
                    {
                        sftpClient.DownloadFile(sourceFilePath, fileStream);
                    }
                }
            }
        }
    }
    
    0 讨论(0)
提交回复
热议问题