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

纵然是瞬间 提交于 2019-11-30 15:55:45

You have to provide a callback to the uploadCallback argument of SftpClient.UploadFile.

public void UploadFile(Stream input, string path, Action<ulong> uploadCallback = null)

And of course, you have to upload on a background thread or use an asynchronous upload (SftpClient.BeginUploadFile).


Example using a background thread (task):

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

private void Upload()
{
    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 = "upload.txt";

        using (var stream = new FileStream(SourcePath + FileName, FileMode.Open))
        using (var client = new SftpClient(Host, Port, Username, Password))
        {
            client.Connect();
            // Set progress bar maximum on foreground thread
            progressBar1.Invoke(
                (MethodInvoker)delegate { progressBar1.Maximum = (int)stream.Length; });
            // Upload with progress callback
            client.UploadFile(stream, RemotePath + FileName, UpdateProgresBar);
            MessageBox.Show("Upload complete");
        }
    }
    catch (Exception e)
    {
        MessageBox.Show(e.Message);
    }
}

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


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

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