winforms 使用SSH.NET在ProgressBar中显示文件上传进度

kuhbmx9i  于 2023-04-21  发布在  .NET
关注(0)|答案(1)|浏览(113)

我想显示我的ProgressBar上传过程的进度,这里是我的按钮的代码“上传”:

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

zqry0prt1#

您必须为SftpClient.UploadFileuploadCallback参数提供回调。

public void UploadFile(
    Stream input, string path, Action<ulong> uploadCallback = null)

当然,您必须在后台线程上上传或使用异步上传(SftpClient.BeginUploadFile)。
使用后台线程(任务)的示例:

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
            int max = (int)stream.Length;
            progressBar1.Invoke(
                (MethodInvoker)delegate { progressBar1.Maximum = max; });
            // 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; });
}

  • 下载 * 见:

Displaying progress of file download in a ProgressBar with SSH.NET

相关问题