private void btnAdd_Click(object sender, RoutedEventArgs e) { string path = tbRef.Text; string name = tbName.Text; if (path != String.Empty && name != String.Empty) { file = new FileDownload(path, name, 100); file._id = id; ProgressBar bar = new ProgressBar(); bar.Maximum = file.ContentLength; bar.Value = file.BytesWritten; ItemElement it = new ItemElement { Id = id, Title = path, Bar = (int)bar.Value }; if (CheckItems(it.Title)) { try { file.Start(it, History, Active); } catch (Exception ex) { tbEx.Text = ex.Message; Delete(file, it); } Items.Add(it); Active.Add(it); id++; threads.Add(file); Serialize(threads.ToArray(), "threads.xml"); Serialize(Items, "items.xml"); } } }
private async Task Start(ItemElement item, ObservableCollection <ItemElement> history, ObservableCollection <ItemElement> active, int range) { if (!_allowedToRun) { throw new InvalidOperationException(); } var request = (HttpWebRequest)WebRequest.Create(_source); request.Method = "GET"; request.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)"; request.AddRange(range); using (var response = await request.GetResponseAsync()) { using (var responseStream = response.GetResponseStream()) { using (var fs = new FileStream(_destination, FileMode.Append, FileAccess.Write, FileShare.ReadWrite)) { item.Status = Statuses.Active; while (_allowedToRun) { var buffer = new byte[_chunkSize]; var bytesRead = await responseStream.ReadAsync(buffer, 0, buffer.Length); if (bytesRead == 0) { break; } await fs.WriteAsync(buffer, 0, bytesRead); BytesWritten += bytesRead; item.Bar = BytesWritten; Application.Current.Dispatcher.Invoke(() => { }); } if ((int)item.Bar >= _contentLength) { item.Status = Statuses.Completed; active.Remove(item); history.Add(item); Application.Current.Dispatcher.Invoke(() => { }); } await fs.FlushAsync(); } } } }
public void Pause(ItemElement item) { _allowedToRun = false; item.Status = Statuses.Paused; }
public Task Start(ItemElement item, ObservableCollection <ItemElement> history, ObservableCollection <ItemElement> active) { _allowedToRun = true; return(Start(item, history, active, BytesWritten)); }
private void Delete(FileDownload file, ItemElement it) { Items.Remove(it); threads.Remove(file); Active.Remove(it); }