C#中WebClient实现文件下载

2019-12-30 16:11:23刘景俊

下面是下载用的核心代码,我们把它分为计算下载百分比和计算当前下载速度分别介绍。


// 获得下载文件的长度
double contentLength = DownloadManager.GetContentLength(myHttpWebClient);
byte[] buffer = new byte[BufferSize];
long downloadedLength = 0;
long currentTimeSpanDataLength = 0;   
int currentDataLength;
while ((currentDataLength = stream.Read(buffer, 0, BufferSize)) > 0 && !this._cancelDownload)
{
 fileStream.Write(buffer, 0, currentDataLength);
 downloadedLength += (long)currentDataLength;
 currentTimeSpanDataLength += (long)currentDataLength;
 int intDownloadSpeed = 0;
 if (this._downloadStopWatch.ElapsedMilliseconds > 800)
 {
  double num5 = (double)currentTimeSpanDataLength / 1024.0;
  double num6 = (double)this._downloadStopWatch.ElapsedMilliseconds / 1000.0;
  double doubleDownloadSpeed = num5 / num6;
  intDownloadSpeed = (int)Math.Round(doubleDownloadSpeed, 0);
  this._downloadStopWatch.Reset();
  this._downloadStopWatch.Start();
  currentTimeSpanDataLength = 0;
 }

 double doubleDownloadPersent = 0.0;
 if (contentLength > 0.0)
 {
  doubleDownloadPersent = (double)downloadedLength / contentLength;
 }
}

在下载的过程中计算下载百分比

首先需要从 http 请求中获得要下载文件的长度,细节请参考本文所配 demo。


double contentLength = DownloadManager.GetContentLength(myHttpWebClient);

每从文件流中读取一次数据,我们知道读了多少个字节(currentDataLength),累计下来就是当前已经下载了的文件长度。


downloadedLength += (long)currentDataLength;

然后做个除法就行了:


doubleDownloadPersent = (double)downloadedLength / contentLength;

计算实时的下载速度

对于当前的下载速度,我们计算过去的一段时间内下载下来的字节数。时间段可以使用 StopWatch 来获得,我选择的时间段要求大于 800 毫秒。


if (this._downloadStopWatch.ElapsedMilliseconds > 800)
{
 /***********************************/
 // 计算上一个时间段内的下载速度
 double num5 = (double)currentTimeSpanDataLength / 1024.0;
 double num6 = (double)this._downloadStopWatch.ElapsedMilliseconds / 1000.0;
 double doubleDownloadSpeed = num5 / num6;
 /***********************************/

 intDownloadSpeed = (int)Math.Round(doubleDownloadSpeed, 0);
 // 本次网速计算完成后重置时间计时器和数据计数器,开始下次的计算
 this._downloadStopWatch.Reset();
 this._downloadStopWatch.Start();
 currentTimeSpanDataLength = 0;
}

事实上每次计算下载速度的时间段长度是不顾定的,但这并不影响计算结果,我只要保证距离上次计算超过了 800 毫秒就行了。

允许用户取消下载

对于一个执行时间比较长的任务来说,不允许用户取消它是被深恶痛绝的!尤其是网速不太好的时候。所以我们需要给用户一个选择:可以痛快(而不是痛苦)的结束当前的旅程。