Calculate download rate in ProgressChanged

1.7k Views Asked by At

So essentially i have a form that downloads a file, called file.jpg that rotates every hour or so for example, and i have a button that starts the download where it randomly downloads it an arbitrary amount of time (mainly this is a self learning exercise) I like to add code in progressChange where I want to somehow grab the bytes received over time to get kb/s. i googled around and can't find anything. i dont need any fancy network stacks, as they are standard jpegs so it isn't too big (in fact by the time the file downloads, when i clear the progress bar, i never saw it to begin with.. but i digress) i like to see the avg kb/s even if i see it for 2 seconds (files are about 1 meg each say). ANy help is much appreciated.

private void btnStart_Click(object sender, EventArgs e)
    {
        btnStart.Enabled = false;
        btnStop.Enabled = true;



        WebClient webclient = new WebClient();           
        webclient.DownloadFileCompleted += new AsyncCompletedEventHandler(Completed);
        webclient.DownloadProgressChanged += new DownloadProgressChangedEventHandler(ProgressChanged);            
        // you need to increment the number !!! 

        // add the file to the list.
        // single click should preview
        // progress bar should clear after it downloads
        // the status bar as well should be done

        int num = nextIndex() + 1;
        string file = @"C:\IMG\IMG_";
        file += string.Format("{0:d5}", num);
        file += ".jpg";

        webclient.DownloadFileAsync(new Uri("http://www.foobar.com/file.jpg"), file);
        lstFiles.Enabled = false;           
    }

 private void ProgressChanged(object sender, DownloadProgressChangedEventArgs e)
    {
        // display kb/sec as well??
        pbDownload.Value = e.ProgressPercentage;

    }
1

There are 1 best solutions below

1
On
private void downloadMyWorkProgress(object sender, DownloadProgressChangedEventArgs e)
{
    double bytesIn = double.Parse(e.BytesReceived.ToString());
    double totalBytes = double.Parse(e.TotalBytesToReceive.ToString());
    double percentage = bytesIn / totalBytes * 100;
    progressBar1.Value = int.Parse(Math.Truncate(percentage).ToString());
}