Displaying progress of file download in a ProgressBar with SSH.NET

纵饮孤独 提交于 2019-12-01 00:25:51

As you correctly did, similarly to the code for displaying progress of file upload, you have to provide a callback to the downloadCallback argument of SftpClient.DownloadFile.

public void DownloadFile(string path, Stream output, Action<ulong> downloadCallback = null)

Also you correctly download on a background thread. Alternatively, you could use an asynchronous upload (SftpClient.BeginDownloadFile).

What is wrong and needs change:

  • You have to open/create the local file for writing (FileMode.Create).
  • You have to retrieve a size of the remote file, not the local one (not existing yet). Use SftpClient.GetAttributes.

Example using a background thread (task):

private void button1_Click(object sender, EventArgs e)
{
    // Run Download on background thread
    Task.Run(() => Download());
}

private void Download()
{
    try
    {
        int Port = 22;
        string Host = "example.com";
        string Username = "username";
        string Password = "password";
        string RemotePath = "/remote/path/";
        string SourcePath = @"C:\local\path\";
        string FileName = "download.txt";

        using (var stream = new FileStream(SourcePath + FileName, FileMode.Create))
        using (var client = new SftpClient(Host, Port, Username, Password))
        {
            client.Connect();
            SftpFileAttributes attributes = client.GetAttributes(RemotePath + FileName);
            // Set progress bar maximum on foreground thread
            progressBar1.Invoke(
                (MethodInvoker)delegate { progressBar1.Maximum = (int)attributes.Size; });
            // Download with progress callback
            client.DownloadFile(RemotePath + FileName, stream, DownloadProgresBar);
            MessageBox.Show("Download complete");
        }
    }
    catch (Exception e)
    {
        MessageBox.Show(e.Message);
    }
}

private void DownloadProgresBar(ulong uploaded)
{
    // Update progress bar on foreground thread
    progressBar1.Invoke((MethodInvoker)delegate { progressBar1.Value = (int)uploaded; });
}


For upload see:
Displaying progress of file upload in a ProgressBar with SSH.NET

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!