2017-04-22 172 views
3

我想告訴我的ProgressBar上載過程的進展,這是我的按鈕「上傳」的代碼:顯示文件上傳進度的進度與SSH.NET

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

回答

7

你必須請提供uploadCallback參數SftpClient.UploadFile的回調。

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

enter image description here


對於下載看到:使用後臺線程(任務)



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

+1

男人,你真的awesom e,對我來說非常合適,萬分感謝。 – Yox