C#使用HttpClient对大文件进行断点上传和下载

  string url = "http://file.cshelloworld.com/images/1771477326069108736.jpg";

  long totalSize = 0;//文件总大小

  long downLoadingSize = 0;//当前已经下载了多少

  private void Button_Click(object sender, RoutedEventArgs e)

  {

  Task.Run(async () =>

  {

  //获取到文件总大小 通过head请求

  using HttpClient client = new HttpClient();

  HttpRequestMessage requestMessage = new HttpRequestMessage(HttpMethod.Head, url);

  var response = await client.SendAsync(requestMessage);

  totalSize = response.Content.Headers.ContentLength.Value;

  using FileStream fileStream = new FileStream("d:a.jpj", FileMode.Create, FileAccess.Write, FileShare.Read);

  //开始分片下载

  while (downLoadingSize < totalSize)

  {

  //组装range 0,1000 1000,2000 0,9999

  long start = downLoadingSize;

  long end = start + 1000;

  if (end > (totalSize - 1))

  {

  end = totalSize - 1;

  }

  client.DefaultRequestHeaders.Range = new System.Net.Http.Headers.RangeHeaderValue(start, end);

  var res = await client.GetAsync(url);

  byte[] bytes = await res.Content.ReadAsByteArrayAsync();

  await fileStream.WriteAsync(bytes, 0, bytes.Length);

  //更新UI的进度

  downLoadingSize += bytes.Length;

  int process = (int)((downLoadingSize / (decimal)totalSize) * 100);

  this.Dispatcher.Invoke(() =>

  {

  cont.Text = process + "%";

  this.processBar.Value = process;

  });

  }

  fileStream.Close();

  });

  }