0

I am working on a tool to download files from SFTP, 2 at a time. I am using Tamir.Sharpssh to connect to the SFTP, and I thought it would be do-able by using async and await. When I run the program, it finishes with no errors but I am not seeing any files downloaded.

Below is my code, thank you in advance!

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;
        }
    }));
}
OHHO
  • 143
  • 2
  • 9

2 Answers2

0

I found the answer. I had to change SFTPFileGetHelper() from void to Task. When the main function calls the SFTPFileGetHelper() it needs to get the result from it, which in this case it will return true if the SFTP download is successful.

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;
    }
}
OHHO
  • 143
  • 2
  • 9
0

You could use Event Handling for check the current progress and the beginning and ending of the upload:

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");
}
Uwe Köhler
  • 123
  • 1
  • 7