Ejemplo n.º 1
0
 //还原下载信息
 protected virtual async Task <bool> LoadDownloadInfoAsync(bool LoadSrc = true)
 {
     try
     {
         if (File.Exists(DownloadInfoFileFullPath))
         {
             var downloadInfoText = File.ReadAllText(DownloadInfoFileFullPath);
             var downloadInfo     = JsonConvert.DeserializeObject <DownloadInfo>(downloadInfoText);
             var count            = downloadInfo.Count(m => m.Size == 0);
             Console.WriteLine("downloadInfo" + count);
             if (LoadSrc)
             {
                 foreach (var item in downloadInfo)
                 {
                     if (item.TotalReadBytes < item.Size)
                     {
                         var httpClient = HttpClientFactory.Instance.GetHttpClient(item.Url ?? Url);
                         httpClient.DefaultRequestHeaders.Range = new RangeHeaderValue(item.Start + item.TotalReadBytes, item.End);
                         item.SrcStream = await httpClient.GetStreamAsync(item.Url ?? Url);
                     }
                 }
             }
             DownloadInfo.AddRange(downloadInfo);
             return(true);
         }
         return(false);
     }
     catch (Exception ex)
     {
         Console.WriteLine(ex.Message);
         return(false);
     }
 }
Ejemplo n.º 2
0
        public virtual async Task LoadAsync()
        {
            //检查参数
            CheckArgument();
            //获取Server文件信息
            DownloadInfo.ServerFileInfo = await ServerHelper.LoadServerInfoAsync(Url);

            //本地文件路径
            var fileName = SuggestedFileName ?? DownloadInfo.ServerFileInfo.Name;

            //文件夹不存在,创建文件夹
            if (!Directory.Exists(DirectoryPath))
            {
                Directory.CreateDirectory(DirectoryPath);
            }
            LocalFileFullPath        = Path.Combine(DirectoryPath, fileName);
            DownloadInfoFileFullPath = Path.Combine(DirectoryPath, $"{fileName}.json");
            var loadSuccess = await LoadDownloadInfoAsync();

            ///没有成功需要重新加载
            if (!loadSuccess)
            {
                if (File.Exists(LocalFileFullPath))
                {
                    using (var localFile = new FileStream(LocalFileFullPath, FileMode.OpenOrCreate, FileAccess.Write, FileShare.ReadWrite))
                    {
                        if (localFile.Length >= DownloadInfo.ServerFileInfo.Size)
                        {
                            IsDownloaded = true;
                            await CompleteAsync(true);

                            return;
                        }
                    }
                }
                //拆分分片
                var fileSegments = await this.LoadFileSegmentsAsync();

                DownloadInfo.AddRange(fileSegments);
                await SaveDownloadInfoAsync();
            }
        }