首页 > 解决方案 > Httpclient getting the download speed

问题描述

could someone help me a little? I'm downloading files and I'm able to get the actual download speed. but I want to change the UNIT from KB/sec to MB/sec if the speed is greater than 1mbps

How do I know if is greater than 1mbps so that I the UNIT will change as well

Here's my current code.

I'm running this in a loop.

for (int i = 0; i < totalCount; i++)
     {
     
    string downloadUrl= LB.Items[i].toString();
    
    
    double currentSize = TotalFileSize; //882672
    string UNIT = "KB/s";
    
    DateTime startTime = DateTime.Now;
     

    await ProgressUpdate(downloadUrl, cts.Token); //the actual download
    
    DateTime endTime = DateTime.Now;
    double t = Math.Round(currentSize / 1024 / (endTime - startTime).TotalSeconds);
    var downloadSpeed = (string.Format("Download Speed: {0}{1}", t, UNIT));

Thank you.

标签: c#httpclient

解决方案


您可以使用一个小助手,例如:

var downloadSpeed = FormatSpeed(TotalFileSize, (endTime - startTime).TotalSeconds);

string FormatSpeed( double size, double tspan )
{
      string message = "Download Speed: {0:N0} {1}";
      if( size/tspan > 1024 * 1024 ) // MB
      {
          return string.Format(message, size/(1024*1204)/tspan, "MB/s");
      }else if( size/tspan > 1024 ) // KB
      {
          return string.Format(message, size/(1024)/tspan, "KB/s");
      }
      else
      {
          return string.Format(message, size/tspan, "B/s");
      }
}

看到它运行:https ://dotnetfiddle.net/MjUW2M

输出:

Download Speed: 10 B/s
Download Speed: 100 B/s
Download Speed: 200 B/s
Download Speed: 100 KB/s
Download Speed: 83 MB/s
Download Speed: 9 MB/s

或稍有变化:https ://dotnetfiddle.net/aqanaT

string FormatSpeed( double size, double tspan )
{
  string message = "Download Speed: ";
  if( size/tspan > 1024 * 1024 ) // MB
  {
      return string.Format(message + "{0:N1} {1}", size/(1024*1204)/tspan, "MB/s");
  }else if( size/tspan > 1024 ) // KB
  {
      return string.Format(message + "{0:N0} {1}", size/1024/tspan, "KB/s");
  }
  else
  {
      return string.Format(message + "{0:N1} {1}", size/1024/tspan, "KB/s");
  }

输出:

Download Speed: 0.0 KB/s
Download Speed: 0.1 KB/s
Download Speed: 0.2 KB/s
Download Speed: 100 KB/s
Download Speed: 83.1 MB/s
Download Speed: 8.5 MB/s

推荐阅读