Search code examples
c#sftp

How to increase progressbar while downloading file using Sftp (C#)


This code execute well. But didn't increase progressBar1.value

using (var client = new SftpClient(host, port, username, password))
{
    client.Connect();
    using (var fileStream = new FileStream(localFilePath, FileMode.Create))
    {
        var sftpFileStream = client.OpenRead(remoteFilePath);
        var fileLength = client.GetAttributes(remoteFilePath).Size;
        var buffer = new byte[1024];
        var totalBytesRead = 0L;
        var bytesRead = 0;

        while ((bytesRead = sftpFileStream.Read(buffer, 0, buffer.Length)) > 0)
        {
            fileStream.Write(buffer, 0, bytesRead);
            totalBytesRead += bytesRead;
            var progress = (double)totalBytesRead / fileLength;
            progressBar1.Invoke((MethodInvoker)delegate
            {
                progressBar1.Value = (int)progress;
            });
        }
                    }
        client.Disconnect();
    }
}

I tried without Invoke

...
...
var progress = (double)totalBytesRead / fileLength;
progressBar1.Invoke((MethodInvoker)delegate
progressBar1.Value = (int)progress;

Both way didn't work. How can I fix this?


Solution

  • You set the value of the progress bar within the range 0.0 to 1.0: progress = (double)totalBytesRead / fileLength;. This has to match the mininum and maximum value as set at the progress bar control. So

    • either set the maximum value of the progress bar control to 1
    • or leave it at 100 and set the value as progress = 100.0 * totalBytesRead / fileLength;