2017-09-01 89 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解决了这个问题。再次感谢 –