使用SSH.NET在ProgressBar中显示文件下载的进度

我想在ProgressBar上显示下载过程的ProgressBar 。 我尝试过这样的代码来上传 ,但我失败了。 这是我尝试失败的一个例子

 private void button5_Click(object sender, EventArgs e) { Task.Run(() => Download()); } private void Download() { try { int Port = (int)numericUpDown1.Value; string Host = comboBox1.Text; string Username = textBox3.Text; string Password = textBox4.Text; string SourcePath = textBox5.Text; string RemotePath = textBox6.Text; string FileName = textBox7.Text; using (var file = File.OpenWrite(SourcePath + FileName)) using (var Stream = new FileStream(SourcePath + FileName, FileMode.Open)) using (var Client = new SftpClient(Host, Port, Username, Password)) { Client.Connect(); progressBar1.Invoke((MethodInvoker) delegate { progressBar1.Maximum = (int)Stream.Length; }); Client.DownloadFile(RemotePath + FileName, /*file*/ Stream, DownloadProgresBar); Client.Disconnect(); } } catch (Exception Ex) { System.Windows.Forms.MessageBox.Show(Ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } } private void DownloadProgresBar(ulong Downloaded) { progressBar1.Invoke((MethodInvoker) delegate { progressBar1.Value = (int)Downloaded; }); } 

先感谢您

正如您所做的那样,与显示文件上载进度的代码类似,您必须提供对SftpClient.DownloadFiledownloadCallback参数的SftpClient.DownloadFile

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

您也可以在后台线程上正确下载。 或者,您可以使用异步上载( SftpClient.BeginDownloadFile )。

有什么不对,需要你改变:

  • 您必须打开/创建用于写入的本地文件( FileMode.Create )。
  • 您必须检索远程文件的大小,而不是本地大小(尚不存在)。 使用SftpClient.GetAttributes

使用后台线程的示例(任务):

 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; }); } 

在此处输入图像描述


上传请参阅:
使用SSH.NET在ProgressBar中显示文件上载的进度