【问题标题】:C# FtpWebRequest progress bar tooltip update with uploaded amountC# FtpWebRequest 进度条工具提示更新上传数量
【发布时间】:2017-09-01 07:47:58
【问题描述】:

我正在尝试将当前上传的数量写入我的uploadProgress 进度条的工具提示,因此当用户将鼠标悬停在进度条上时,可以看到工具提示根据文件大小更改显示上传的数量。 到目前为止,当我将鼠标悬停在文件上时,我的代码会显示“忙碌”图标,直到文件上传完成,然后它会显示下载的数量和文件大小。

有人可以帮我解决这个问题吗?

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

谢谢

【问题讨论】:

  • 告诉我们你怎么称呼uploadFile

标签: c# .net winforms ftp ftpwebrequest


【解决方案1】:

您的代码对我有用。假设您在后台线程上运行 uploadFile,例如:

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

另见How can we show progress bar for upload with FtpWebRequest
(虽然你已经知道那个链接了)


您只是太频繁地更新工具提示,所以它会闪烁。

【讨论】:

  • 感谢 Martin,它尝试了 'task.Run' 行,并且它工作正常,...但我必须删除对我拥有的 Richtextbox 的任何写入,否则我会得到 'Cross-Thread operation not有效的。控件“richtextbox1”从创建它的线程以外的线程访问。有没有办法解决这个问题?
  • 访问uploadProgresstoolTip1 的方式相同。使用Control.Invoke
  • 别担心,stackoverflow.com/questions/8738767/… 为我解决了这个问题。再次感谢
猜你喜欢
  • 1970-01-01
  • 2011-09-14
  • 2020-10-07
  • 1970-01-01
  • 2016-11-11
  • 1970-01-01
  • 2012-08-06
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多