C# 下载速度测试

C# 下载速度测试,c#,stream,bandwidth,download-speed,C#,Stream,Bandwidth,Download Speed,我正在用C#编写一个应用程序来测量和显示下载速度。我有下面的代码来下载一个62MB的文件,对于我的目的来说,它似乎工作得很好。我计划扩展它来测量每个块所需的时间,这样就可以用图表表示了 在这样做之前,我有几个问题要确保它确实在做我认为它正在做的事情。代码如下: private void DownloadFile() { string uri = ConfigurationManager.AppSettings["DownloadFile"].ToString(); HttpWebRequ

我正在用C#编写一个应用程序来测量和显示下载速度。我有下面的代码来下载一个62MB的文件,对于我的目的来说,它似乎工作得很好。我计划扩展它来测量每个块所需的时间,这样就可以用图表表示了

在这样做之前,我有几个问题要确保它确实在做我认为它正在做的事情。代码如下:

private void DownloadFile()
{
  string uri = ConfigurationManager.AppSettings["DownloadFile"].ToString();
  HttpWebRequest request = (HttpWebRequest)WebRequest.Create(new Uri(uri));

  int intChunkSize = 1048576; //  1 MB chunks

  using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
  {
    byte[] buffer = new byte[intChunkSize];
    int intStatusCode = (int)response.StatusCode;
    if (intStatusCode >= 200 && intStatusCode <= 299)   //  success
    {
      Stream sourceStream = response.GetResponseStream();
      MemoryStream memStream = new MemoryStream();
      int intBytesRead;
      bool finished = false;
      while (!finished)
      {
        intBytesRead= sourceStream.Read(buffer, 0, intChunkSize);
        if (intBytesRead > 0)
        {
          memStream.Write(buffer, 0, intBytesRead);
          //  gather timing info here
        }
        else
        { 
          finished = true;
        }
      } 
    }   
  } 
}   
private void DownloadFile()
{
字符串uri=ConfigurationManager.AppSettings[“DownloadFile”].ToString();
HttpWebRequest请求=(HttpWebRequest)WebRequest.Create(新Uri(Uri));
int intChunkSize=1048576;//1 MB块
使用(HttpWebResponse=(HttpWebResponse)request.GetResponse())
{
字节[]缓冲区=新字节[intChunkSize];
int intStatusCode=(int)response.StatusCode;
如果(intStatusCode>=200&&intStatusCode 0)
{
memStream.Write(缓冲区,0,intBytesRead);
//在这里收集时间信息
}
其他的
{ 
完成=正确;
}
} 
}   
} 
}   
问题是:

  • 响应实例化时是否包含所有数据,还是仅包含头信息?response.ContentLength确实反映了正确的值

  • 尽管我使用的是1MB块大小,但每次迭代中实际读取的字节数(intBytesRead)要少得多,通常是16384字节(16KB),但有时是1024字节(1KB)。为什么会这样

  • 有没有办法强迫它实际读取1MB块

  • 将数据实际写入MemoryStream有什么作用吗

  • 谢谢