Пример #1
0
        /// <summary>
        /// 执行DownloadFile
        /// </summary>
        /// <param name="downloadFile"></param>
        /// <returns></returns>
        public async Task <bool> DoDownloadFile(DownloadFile downloadFile)
        {
            using (HttpClient httpClient = new HttpClient()
            {
                Timeout = TimeSpan.FromSeconds(30)
            })
            {
                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;   //服务器上的文件大小
                    }
                    long?length = (httpResponseMessage.Content.Headers.ContentRange == null ?      //如果为空,则说明服务器不支持断点续传
                                   httpResponseMessage.Content.Headers.ContentLength :
                                   httpResponseMessage.Content.Headers.ContentRange.Length) ?? -1; //服务器上的文件大小
                    string md5 = downloadFile.MD5 ?? (httpResponseMessage.Content.Headers.ContentMD5 == null ? null : Convert.ToBase64String(httpResponseMessage.Content.Headers.ContentMD5));
                    if (downloadFile.DoLocal(length, md5))
                    {
                        using (Stream stream = await httpResponseMessage.Content.ReadAsStreamAsync())
                        {
                            stream.ReadTimeout = 10 * 1000;
                            bool success = await Download(stream, downloadFile) & await downloadFile.Release();

                            this.OnDownloadCompleted(new CompletedArgs(success));
                            return(success);
                        }
                    }
                    else
                    {
                        this.OnDownloadError(new ErrorArgs("服务器的上的版本已经变化"));
                        return(false);
                    }
                }
                catch (Exception ex)
                {
                    this.OnDownloadError(new ErrorArgs(ex.Message));
                    return(false);
                }
            }
        }