private void OnDownloadFinished(object sender, AsyncCompletedEventArgs e) { BookEventArg file = e.UserState as BookEventArg; if (e.Cancelled) { file.Status = -1; } else if (e.Error != null) //Failed { file.Status = e.Error.HResult; } else //Success { file.Status = 0; } BookDownloadCompleted?.Invoke(this, file); _downloaders.Remove(file.URL); }
protected void DownloadBook(BookEventArg e) { if (IsCancel) { e.Status = -1; e.Progress = 100; BookDownloadCompleted?.Invoke(this, e); return; } WebClient webClient = null; if (_downloaders.ContainsKey(e.URL)) { webClient = _downloaders[e.URL]; } else { webClient = new WebClient(); webClient.DownloadFileCompleted += new AsyncCompletedEventHandler(OnDownloadFinished); webClient.DownloadProgressChanged += new DownloadProgressChangedEventHandler(OnDownloadProgressChanged); _downloaders.Add(e.URL, webClient); } if (IsCancel) { e.Status = -1; e.Progress = 100; BookDownloadCompleted?.Invoke(this, e); return; } if (webClient != null) { if (webClient.IsBusy) { webClient.CancelAsync(); } if (File.Exists(e.Path)) { System.IO.FileInfo fi = new FileInfo(e.Path); if (fi.Length > 0) { BookDownloadingFileExist?.Invoke(this, e); if (!e.Overwriten) { e.Status = 2; e.Progress = 100; BookDownloadCompleted?.Invoke(this, e); return; } } } if (IsCancel) { e.Status = -1; e.Progress = 100; BookDownloadCompleted?.Invoke(this, e); return; } try { if (EnsureDirectoryExist(e.Path)) { webClient.DownloadFile(new Uri(e.URL), e.Path); e.Status = 0; } else { e.Status = -1; } e.Progress = 100; BookDownloadCompleted?.Invoke(this, e); return; } catch (Exception ex) { e.Status = 1; e.Progress = 100; BookDownloadCompleted?.Invoke(this, e); return; } } }