2017-09-01 83 views
1

我想寫入我的uploadProgress進度條工具提示當前上傳量,因此當用戶鼠標懸停進度條時,可以看到更改顯示上傳量的工具提示文件大小。 我到目前爲止的代碼給我「忙」圖標時,我將鼠標懸停,直到文件完成上傳,然後它顯示下載的數量和文件大小。C#FtpWebRequest進度條工具提示更新與上傳量

有人可以幫我搞定這個工作嗎?

private void uploadFile() 
{ 
    try 
    { 
     richTextBox1.AppendText("\n\nStarting file upload"); 
     FtpWebRequest request = 
      (FtpWebRequest)WebRequest.Create("ftp://ftpsite.com/public_html/test.htm"); 

     request.Credentials = new NetworkCredential("username", "password"); 

     request.UsePassive = true; 
     request.UseBinary = true; 
     request.KeepAlive = true; 

     request.Method = WebRequestMethods.Ftp.UploadFile; 

     using (Stream fileStream = File.OpenRead(@"C:\path\testfile.UPLOAD")) 
     using (Stream ftpStream = request.GetRequestStream()) 
     { 
      uploadProgress.Invoke(
       (MethodInvoker)delegate { 
        uploadProgress.Maximum = (int)fileStream.Length; }); 

      byte[] buffer = new byte[10240]; 
      int read; 
      while ((read = fileStream.Read(buffer, 0, buffer.Length)) > 0) 
      { 
       ftpStream.Write(buffer, 0, read); 
       uploadProgress.Invoke(
        (MethodInvoker)delegate { 
         uploadProgress.Value = (int)fileStream.Position; 

         toolTip1.SetToolTip(
          uploadProgress, string.Format("{0} MB's/{1} MB's\n", 
          (uploadProgress.Value/1024d/1024d).ToString("0.00"), 
          (fileStream.Length/1024d/1024d).ToString("0.00"))); 
        });  
      } 
     } 
    } 
    catch (Exception ex) 
    { 
     MessageBox.Show(ex.Message); 
    } 
} 

感謝

+0

向我們展示如何調用'uploadFile'。 –

回答

1

您的代碼爲我工作。假設你在後臺線程運行uploadFile,如:

private void button1_Click(object sender, EventArgs e) 
{ 
    Task.Run(() => uploadFile()); 
} 

enter image description here

參見How can we show progress bar for upload with FtpWebRequest
(雖然你已知道鏈接)


您只需更新提示過經常,所以它閃爍。

+0

感謝馬丁,它試圖'task.Run'行,它的工作原理,...但我不得不刪除任何寫入我有richtextbox,否則我得到'跨線程操作無效。從其創建線程以外的線程訪問控件'richtextbox1'。無論如何要解決這個問題嗎? –

+0

就像訪問'uploadProgress'和'toolTip1'一樣。使用'Control.Invoke'。 –

+0

別擔心,https://stackoverflow.com/questions/8738767/backgroundworker-cross-thread-operation-not-valid解決了這個問題。再次感謝 –