C# Httpclient获得下载速度

C# Httpclient获得下载速度,c#,httpclient,C#,Httpclient,谁能帮我一点忙吗? 我正在下载文件,我能够得到实际的下载速度。但是如果速度大于1mbps,我想把单位从KB/秒改为MB/秒 我如何知道是否大于1mbps,以便我也能更改装置 这是我目前的密码 我在循环中运行这个 for (int i = 0; i < totalCount; i++) { string downloadUrl= LB.Items[i].toString(); double currentSize = TotalFil

谁能帮我一点忙吗? 我正在下载文件,我能够得到实际的下载速度。但是如果速度大于1mbps,我想把单位从KB/秒改为MB/秒

我如何知道是否大于1mbps,以便我也能更改装置

这是我目前的密码

我在循环中运行这个

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));
for(int i=0;i

谢谢。

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

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");
      }
}
查看它的运行:

输出:

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
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
或者一个微小的变化:

输出:

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
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

if(t>1024.0){t/=1024.0;UNIT=“MB/s”;}
或者你的确切意思是什么?我想是这样的。我要试试这个装置仍然没有改变。1528KB/sec仍然是kbwoow!现在要测试它。非常感谢。它现在工作了。这就是我要寻找的。我如何在下载时看到实时速度?只有在结束时间后显示的结果取决于你下载的确切代码。是吗您使用的是
HttpClient
?可能会询问有关此部分的其他问题,并将其链接到此处。然后我会看一看。是的,我正在使用HttpClient。谢谢。如果可以,我会先尝试。如果不行,我会稍后发布我的问题。这是关于实时下载速度的新问题