本文介绍了使用SSH.NET在ProgressBar中显示文件上传的进度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想在我的ProgressBar
上显示上传过程的进度,这是我的按钮上传"的代码:
I want to show the progress of an uploading process on my ProgressBar
, Here is the code of my button "Upload":
private void button2_Click(object sender, EventArgs e)
{
int Port = int.Parse(textBox2.Text);
string Host = textBox1.Text;
string Username = textBox3.Text;
string Password = textBox4.Text;
string WorkingDirectory = textBox6.Text;
string UploadDirectory = textBox5.Text;
FileInfo FI = new FileInfo(UploadDirectory);
string UploadFile = FI.FullName;
Console.WriteLine(FI.Name);
Console.WriteLine("UploadFile" + UploadFile);
var Client = new SftpClient(Host, Port, Username, Password);
Client.Connect();
if (Client.IsConnected)
{
var FS = new FileStream(UploadFile, FileMode.Open);
if (FS != null)
{
Client.UploadFile(FS, WorkingDirectory + FI.Name, null);
Client.Disconnect();
Client.Dispose();
MessageBox.Show(
"Upload complete", "Information", MessageBoxButtons.OK,
MessageBoxIcon.Information);
}
}
}
推荐答案
您必须提供对 SftpClient.UploadFile
.
You have to provide a callback to the uploadCallback
argument of SftpClient.UploadFile
.
public void UploadFile(Stream input, string path, Action<ulong> uploadCallback = null)
当然,您必须在后台线程上上传或使用异步上传( SftpClient.BeginUploadFile
).
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; });
}
有关下载的信息,请参见:
在带有SSH.NET的ProgressBar中显示文件下载进度
For download see:
Displaying progress of file download in a ProgressBar with SSH.NET
这篇关于使用SSH.NET在ProgressBar中显示文件上传的进度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!