Displaying FTP/SFTP transfer progress on WinForms ProgressBar

The following example shows how to use WinSCP .NET assembly together with WinForms to display progress of files transfer in GUI. If you have another preferred language, you can easily translate it.

The code uses Session.FileTransferProgress event.

The example assumes that you have a form with two controls, ProgressBar (progressBar1) and Button (button1).

C#

private void button1_Click(object sender, EventArgs e)
{
    // Run Upload on a background thread
    Task.Run(() => Upload());
}
 
private void Upload()
{
    try
    {
        using (var session = new Session())
        {
            var sessionOptions = new SessionOptions
            {
                Protocol = Protocol.Sftp,
                HostName = "example.com",
                UserName = "user",
                Password = "mypassword",
                SshHostKeyFingerprint = "ssh-rsa 2048 xxxxxxxxxxx..."
            };
 
            session.FileTransferProgress += (sender, e) =>
                {
                    progressBar1.Invoke((MethodInvoker)(() => { 
                        progressBar1.Value = (int)(e.OverallProgress * 100); }));
                };
 
            session.Open(sessionOptions);
 
            session.PutFilesToDirectory(localDirectory, remoteDirectory).Check();
 
            MessageBox.Show("Upload complete");
        }
    }
    catch (Exception e)
    {
        MessageBox.Show(e.Message);
    }
}

VB.NET

Private Sub button1_Click(sender As Object, e As EventArgs) Handles button1.Click
    ' Run Upload on a background thread
    Task.Run(Sub() Upload())
End Sub
 
Private Sub Upload()
    Try
        Using session As New Session
            Dim sessionOptions As New SessionOptions
            With sessionOptions
                .Protocol = Protocol.Sftp
                .HostName = "example.com"
                .UserName = "user"
                .Password = "mypassword"
                .SshHostKeyFingerprint = "ssh-rsa 2048 xxxxxxxxxxx..."
            End With
 
            AddHandler session.FileTransferProgress,
                Sub(sender, e) progressBar1.Invoke(
                    Sub()
                        progressBar1.Value = CInt(e.OverallProgress * 100)
                    End Sub)
 
            session.Open(sessionOptions)
 
            session.PutFilesToDirectory(localDirectory, remoteDirectory).Check()
 
            MessageBox.Show("Upload complete")
        End Using
    Catch e As Exception
        MessageBox.Show(e.Message)
    End Try
End Sub

Last modified: by martin