如何从SftpClient类中止一个Action' DownloadFile()函数(SSH.NET)?

时间:2018-04-09 02:20:55

标签: c# .net ssh sftp ssh.net

我使用SSH.NET通过安全SSH/SFTP连接实现文件下载。我还需要能够看到下载的进度,并能够在用户需要时中止它。所以代码看起来像这样:

ConnectionInfo conn = new PasswordConnectionInfo(host, port, username, password);
SftpClient sshSFTP = new SftpClient(conn);
sshSFTP.Connect();

try
{
    FileStream streamFile = File.Create(strLocalFilePath);

    sshSFTP.DownloadFile(strFilePath, streamFile,
        (ulong uiProcessedSize) =>
        {
            //Callback
            processProgress(uiProcessedSize);

            if(didUserAbortDownload())
            {
                //Aborted
                throw new Exception("Aborted by the user");
            }
        });
}
catch (Exception ex)
{
    Console.WriteLine("Download failed: " + ex.Message);
}

streamFile.Close();
sshSFTP.Disconnect();

我无法找到任何记录的方法来中止Action方法的DownloadFile回调函数,因此我使用了抛出异常。

但是这种方法的问题在于我的自定义异常没有被捕获。

知道如何解决这个问题吗?

2 个答案:

答案 0 :(得分:0)

您可以使用他们的异步(尽管not true async)流程,即BeginDownloadFile。该方法返回的IAsyncResult实现SftpDownloadAsyncResult通过其IsDownloadCanceled属性公开取消。

答案 1 :(得分:0)

除了使用异步接口,如@ejohnson所建议的那样,你也可以关闭输出流:

try
{
    FileStream streamFile = File.Create(strLocalFilePath);

    sshSFTP.DownloadFile(strFilePath, streamFile,
        (ulong uiProcessedSize) =>
        {
            //Callback
            processProgress(uiProcessedSize);

            if(didUserAbortDownload())
            {
                //Aborted
                streamFile.Close();
            }
        });
}
catch (Exception ex)
{
    if(didUserAbortDownload())
    {
        Console.WriteLine("Download cancelled");
    }
    else
    {
        Console.WriteLine("Download failed: " + ex.Message);
    }
}