Exemple #1
0
        /// <summary>
        /// 开始下载文件
        /// </summary>
        /// <returns></returns>
        public async Task DownloadFile()
        {
            var(response, contentLength) = await GetContentLength();

            lStartPos = 0;
            if (System.IO.File.Exists(File.FullName))//另外如果文件已经下载完毕,就不需要再断点续传了,不然请求的range 会不合法会抛出异常。
            {
                FileStream = System.IO.File.OpenWrite(File.FullName);
                lStartPos  = FileStream.Length;
                FileStream.Seek(lStartPos, System.IO.SeekOrigin.Current); //移动文件流中的当前指针
            }
            else
            {
                FileStream = new FileStream(File.FullName, System.IO.FileMode.Create);
                lStartPos  = 0;
            }
            FileStream.SetLength(contentLength);
            FileWriter = new RandomFileWriter(FileStream);

            SegmentManager = new SegmentManager(contentLength);

            _progress.Report(new DownloadProgress($"file length = {contentLength}", SegmentManager));

            var downloadSegment = SegmentManager.GetNewDownloadSegment();

            // 下载第一段
            Download(response, downloadSegment);

            var supportSegment = await TryDownloadLast(contentLength);

            var threadCount = 1;

            if (supportSegment)
            {
                // 多创建几个线程下载
                threadCount = 10;

                for (var i = 0; i < threadCount; i++)
                {
                    Download(SegmentManager.GetNewDownloadSegment());
                }
            }

            for (var i = 0; i < threadCount; i++)
            {
                _ = Task.Run(DownloadTask);
            }

            await FileDownloadTask.Task;
        }
Exemple #2
0
 public DownloadProgress(string message, SegmentManager segmentManager)
 {
     Message        = message;
     SegmentManager = segmentManager;
 }
Exemple #3
0
 public DownloadProgress(SegmentManager segmentManager)
 {
     SegmentManager = segmentManager;
 }