/// <summary> /// 断点续传下载 /// </summary> /// <param name="uri"></param> /// <returns></returns> public async void ResumeDownload(string partPath) { bool success = false; using (FileStream fileStream = System.IO.File.Open(partPath, FileMode.Open)) using (HttpClient httpClient = new HttpClient() { Timeout = TimeSpan.FromSeconds(30) }) { DownloadFile downloadFile = DownloadFile.FromFileStream(fileStream); if (downloadFile == null) //为空说明已经完成 { success = true; } else { try { httpClient.DefaultRequestHeaders.Range = new RangeHeaderValue(downloadFile.RangeBegin, null); HttpResponseMessage httpResponseMessage = await httpClient.GetAsync(downloadFile.URL, HttpCompletionOption.ResponseHeadersRead); long?contentLength = httpResponseMessage.Content.Headers.ContentLength; if (httpResponseMessage.Content.Headers.ContentRange != null) //如果为空,则说明服务器不支持断点续传 { contentLength = httpResponseMessage.Content.Headers.ContentRange.Length; //服务器上的文件大小 } string md5 = httpResponseMessage.Content.Headers.ContentMD5 == null ? null : Convert.ToBase64String(httpResponseMessage.Content.Headers.ContentMD5); if (md5 != downloadFile.MD5) { throw new Exception("服务器的上的版本已经变化"); } Stream stream = await httpResponseMessage.Content.ReadAsStreamAsync(); stream.ReadTimeout = 10 * 1000; await Download(stream, fileStream, downloadFile); if (fileStream.Length == downloadFile.Length) { if (md5 == null || md5 == MD5Tools.GetFileMd5(partPath)) { success = true; } } else { success = false; } } catch (Exception ex) { //请求错误 this.OnDownloadError(new ErrorArgs(ex.Message)); } } } if (success) { try { System.IO.File.Move(partPath, partPath.Replace(".downloadPart", "")); } catch (Exception ex) { this.OnDownloadError(new ErrorArgs(ex.Message)); } } this.OnDownloadCompleted(new CompletedArgs(success)); }