C#FtpWebRequest进度条工具提示更新,上传金额

时间:2017-09-01 07:47:58

标签: c# .net winforms ftp ftpwebrequest

我正在尝试写入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);
    }
}

由于

1 个答案:

答案 0 :(得分: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
(虽然你已经知道这个链接)

您只是经常更新工具提示,因此它会闪烁。