Gerald Oakham
Gerald Oakham

Reputation: 173

C# FtpWebRequest progress bar tooltip update with uploaded amount

I'm trying to write to my uploadProgress progress bar's toolTip the current uploaded amount, so when the user mouseovers the progress bar, the can see the tooltip changing showing the uploaded amount against the file size. the code I have so far give me the "busy" icon when I mouse over, until the file has finished uploaded, and then it shows the downloaded amount and file size.

Could someone help me get this working ?

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

Thanks

Upvotes: 1

Views: 146

Answers (1)

Martin Prikryl
Martin Prikryl

Reputation: 202292

Your code works for me. Assuming you run the uploadFile on a background thread, like:

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

enter image description here

See also How can we show progress bar for upload with FtpWebRequest
(though you know that link already)


You just update the tooltip too often, so it flickers.

Upvotes: 1

Related Questions