Ejemplo n.º 1
0
        private async Task DownloadAsync(DownloadItem item)
        {
            try {
                if (!Directory.Exists(item.Directory))
                {
                    Directory.CreateDirectory(item.Directory);
                }

                AdvancedWebClient client = UseResumableClient ? new ResumableWebClient() : new AdvancedWebClient();
                using (client) {
                    if (Proxy != null)
                    {
                        client.Proxy = Proxy;
                    }
                    client.DownloadProgressChanged += (s, e) => {
                        item.TotalBytes    = e.TotalBytesToReceive;
                        item.ReceivedBytes = e.BytesReceived;
                    };
                    client.SetRequest += (s, e) => {
                        HttpWebRequest request = e.Data;
                        request.Referer         = item.Referer;
                        request.CookieContainer = Cookies;
                        if (!item.UserName.IsNullOrEmpty() || !item.Password.IsNullOrEmpty())
                        {
                            request.Headers.Set(AdvancedWebClient.AuthorizationHeaderName,
                                                AdvancedWebClient.GetBasicAuthenticationHeader(item.UserName, item.Password));
                        }
                    };

                    item.Download();
                    CancellationTokenSource source = new CancellationTokenSource();
                    _downloadingItems[item] = source;
                    await client.DownloadFileAsync(item.Uri, item.FilePath, source.Token).ConfigureAwait(false);
                }

                if (IsDownloadedFileCorrupted(item))
                {
                    item.Start();
                }
                else
                {
                    item.Complete();
                }
            }
            catch (OperationCanceledException) {
                FileInfo file = new FileInfo(item.FilePath);
                if (file.Exists)
                {
                    item.ReceivedBytes = file.Length;
                }
            }
            catch (Exception) {
                item.Error();
            }
        }
Ejemplo n.º 2
0
        private bool IsDownloadedFileCorrupted(DownloadItem item)
        {
            DownloadCompletingEventArgs e = new DownloadCompletingEventArgs(item);

            DownloadCompleting?.Invoke(this, e);

            if (e.IsCorrupted)
            {
                item.Error();
            }
            return(e.IsCorrupted);
        }