在ProgressChanged中计算下载速率

时间:2011-11-30 00:56:02

标签: c# webclient downloadfileasync

所以基本上我有一个下载文件的表单,名为file.jpg,每小时左右旋转一次,例如,我有一个按钮开始下载,随机下载任意时间(主要是一个自学习练习)我喜欢在progressChange中添加代码,我想以某种方式获取随时间收到的字节以获得kb / s。我用Google搜索,找不到任何东西。我不需要任何花哨的网络堆栈,因为它们是标准的jpegs所以它不是太大(实际上在文件下载时,当我清除进度条时,我从未看到它开始...但我离题)我喜欢看avg kb / s,即使我看到它2秒钟(文件大约每个说1兆)。非常感谢你的帮助。

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 个答案:

答案 0 :(得分:1)

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