使用 Tamir.Sharpssh 的 SFTP 多个异步下载

SFTP Multiple Async Downloads using Tamir.Sharpssh

我正在开发一种从 SFTP 下载文件的工具,一次下载 2 个文件。我正在使用 Tamir.Sharpssh 连接到 SFTP,我认为它可以通过使用 async 和 await 来实现。当我 运行 程序完成时没有错误,但我没有看到任何文件下载。

下面是我的代码,先谢谢了!

private async static void SFTPFileGetHelper()
{
    try
    {
        Task<String> task1 = GetFileAsync(sftpFile1, localFile1);
        Task<String> task2 = GetFileAsync(sftpFile2, localFile2);
        await Task.WhenAll(task1, task2);
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex.Message);
    }
}

public static Task<String> GetFileAsync(string remoteFilePath, string localFilePath)
{
    return (Task.Run(() =>
    {
        try
        {
            Sftp conn = new Sftp(Host, Username, Password);
            conn.Connect();
            conn.Get(remoteFilePath, localFilePath);
            conn.Close();
            return remoteFilePath;
        }
        catch(Exception ex)
        {
            return ex.Message;
        }
    }));
}

我找到了答案。 我不得不将 SFTPFileGetHelper() 从 void 更改为 Task。 当主函数调用 SFTPFileGetHelper() 时,它需要从中获取结果,在本例中,如果 SFTP 下载成功,它将 return 为真。

private async static Task<bool> SFTPFileGetHelper()
{
    try
    {
        Task<String> task1 = GetFileAsync(sftpFile1, localFile1);
        Task<String> task2 = GetFileAsync(sftpFile2, localFile2);
        await Task.WhenAll(task1, task2);
        return true;
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex.Message);
        return false;
    }
}

您可以使用事件处理来检查当前进度以及上传的开始和结束:

Sftp.OnTransferStart += new FileTransferEvent(sshCp_OnTransferStart);
Sftp.OnTransferProgress += new FileTransferEvent(sshCp_OnTransferProgress);
Sftp.OnTransferEnd += new FileTransferEvent(sshCp_OnTransferEnd);


private void sshCp_OnTransferStart(string src, string dst, int transferredBytes, int totalBytes, string message)
{
    Console.WriteLine("sshCp_OnTransferStart: " + transferredBytes + "Bytes");
}

private void sshCp_OnTransferProgress(string src, string dst, int transferredBytes, int totalBytes, string message)
{
    Console.WriteLine("sshCp_OnTransferProgress: " + transferredBytes + "Bytes");
}

private void sshCp_OnTransferEnd(string src, string dst, int transferredBytes, int totalBytes, string message)
{
    Console.WriteLine("sshCp_OnTransferEnd: " + transferredBytes + "Bytes");
}