C# FtpWebRequest 进度条工具提示更新上传量

C# FtpWebRequest progress bar tooltip update with uploaded amount

我正在尝试将当前上传量写入我的 uploadProgress 进度条的工具提示,因此当用户将鼠标悬停在进度条上时,可以看到工具提示发生变化,显示上传量与文件大小的对比。 到目前为止,当我将鼠标悬停在上面时,我的代码会给我 "busy" 图标,直到文件上传完成,然后它会显示下载量和文件大小。

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

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,例如:

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

另见 How can we show progress bar for upload with FtpWebRequest
(虽然你已经知道 link)


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