我想在ProgressBar
上显示下载过程的进度。我尝试过像this code for upload这样的事情,但我失败了。这是我尝试失败的一个例子
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;
});
}
提前谢谢
答案 0 :(得分:5)
正如您所做的那样,与displaying progress of file upload的代码类似,您必须回复SftpClient.DownloadFile
的downloadCallback
参数。
public void DownloadFile(string path, Stream output, Action<ulong> 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; });
}
上传请参阅:
Displaying progress of file upload in a ProgressBar with SSH.NET