//Begin downloading the file at the specified url, and save it to the given folder. public void Download(string url, string destFolder) { DownloadData data = null; canceled = false; try { // get download details data = DownloadData.Create(url, destFolder, proxy); // Find out the name of the file that the web server gave us. string destFileName = Path.GetFileName(data.Response.ResponseUri.ToString()); // The place we're downloading to (not from) must not be a URI, // because Path and File don't handle them... destFolder = destFolder.Replace("file:///", "").Replace("file://", ""); downloadingTo = Path.Combine(destFolder, destFileName); // Create the file on disk here, so even if we don't receive any data of the file // it's still on disk. This allows us to download 0-byte files. if (!File.Exists(downloadingTo)) { FileStream fs = File.Create(downloadingTo); fs.Close(); } // create the download buffer byte[] buffer = new byte[downloadBlockSize]; int readCount; // update how many bytes have already been read long totalDownloaded = data.StartPoint; bool gotCanceled = false; while ((int)(readCount = data.DownloadStream.Read(buffer, 0, downloadBlockSize)) > 0) { // break on cancel if (canceled) { gotCanceled = true; data.Close(); break; } // update total bytes read totalDownloaded += readCount; // save block to end of file SaveToFile(buffer, readCount, downloadingTo); // send progress info if (data.IsProgressKnown) { RaiseProgressChanged(totalDownloaded, data.FileSize); } // break on cancel if (canceled) { gotCanceled = true; data.Close(); break; } } if (!gotCanceled) { OnDownloadComplete(); } } catch (UriFormatException e) { throw new ArgumentException( String.Format("Could not parse the URL \"{0}\" - it's either malformed or is an unknown protocol.", url), e); } finally { if (data != null) { data.Close(); } } }
public override IEnumerable <string> Process(string fileName) { if (removeOldFile && new FileInfo(fileName).Exists) { new FileInfo(fileName).Delete(); } using (DownloadData data = DownloadData.Create(url, fileName)) { bool bShowProgress = data.IsProgressKnown; if (bShowProgress) { Progress.SetRange(0, data.FileSize); } // send the new download state Progress.SetMessage("Downloading ..."); // create the download buffer byte[] buffer = new byte[downloadBlockSize]; int readCount; // update how many bytes have already been read long totalDownloaded = data.StartPoint; using (FileStream f = File.Open(fileName, FileMode.Create, FileAccess.Write)) { // read a block of bytes and get the number of bytes read while ((int)(readCount = data.DownloadStream.Read(buffer, 0, downloadBlockSize)) > 0) { // break on cancel if (Progress.IsCancellationPending()) { throw new UserTerminatedException(); } // update total bytes read totalDownloaded += readCount; // send progress info if (bShowProgress) { Progress.SetPosition(totalDownloaded); } else { Progress.SetMessage("Downloaded " + totalDownloaded + " bytes ..."); } // save block to end of file f.Write(buffer, 0, readCount); // break on cancel if (Progress.IsCancellationPending()) { throw new UserTerminatedException(); } } // send 100% completion if url size is known and user hasn't cancelled if (bShowProgress) { Progress.SetPosition(data.FileSize); } else { Progress.SetMessage("Finished, downloaded " + totalDownloaded + " bytes"); } } } return(new string[] { fileName }); }
/// <summary> /// Begins downloading the files. /// </summary> private void BeginDownload() { DownloadData _downloadData = null; FileStream _fileStream = null; try { FileManager.CreateDirectory(_downloadDirectory); // Start the stop stop watch for speed calculation. _stopWatch.Start(); // Receive download details _waitingForResponse = true; _downloadData = new DownloadData(_currentUrl, _downloadDirectory); _downloadData.Create(); _waitingForResponse = false; // Reset the adler _downloaderAdler32.Reset(); DownloadingTo = _downloadData.OutputFilePath; _downloadedFiles.Add(DownloadingTo); if (!File.Exists(DownloadingTo)) { // Create the file. _fileStream = File.Open(DownloadingTo, FileMode.Create, FileAccess.Write); } else { // Read in the existing data to calculate the Adler32 if (Adler32 != 0) { GetAdler32(DownloadingTo); } // Append to an existing file (resume the download) _fileStream = File.Open(DownloadingTo, FileMode.Append, FileAccess.Write); } var _buffer = new byte[_bufferSize]; int _readCount; // Update how many bytes have already been read. _sentSinceLastCalc = _downloadData.StartPoint; // For BPS (bytes/per second) calculation // Only increment once for each %. var _lastProgress = 0; while ((_readCount = _downloadData.DownloadStream.Read(_buffer, 0, _bufferSize)) > 0) { // Break on cancel if (_backgroundDownloader.CancellationPending) { _downloadData.Close(); _fileStream.Close(); break; } // Update total bytes read _downloadData.StartPoint += _readCount; // Update the Adler32 value if (Adler32 != 0) { _downloaderAdler32.Update(_buffer, 0, _readCount); } // Save block to end of file _fileStream.Write(_buffer, 0, _readCount); CalculateBps(_downloadData.StartPoint, _downloadData.TotalDownloadSize); // Send progress info. if (!_backgroundDownloader.CancellationPending && (_downloadData.PercentDone > _lastProgress)) { _backgroundDownloader.ReportProgress(0, new object[] { // use the relative or the raw progress. UseRelativeProgress?GetRelativeProgress(0, _downloadData.PercentDone) : _downloadData.PercentDone, // unweighted percent _downloadData.PercentDone, _downloadSpeed, ProgressStatus.None, null }); _lastProgress = _downloadData.PercentDone; } // Break on cancel if (_backgroundDownloader.CancellationPending) { _downloadData.Close(); _fileStream.Close(); break; } } } catch (UriFormatException e) { VisualExceptionDialog.Show(new Exception($"Could not parse the URL \"{_currentUrl}\" - it's either malformed or is an unknown protocol.", e)); } catch (Exception e) { if (string.IsNullOrEmpty(DownloadingTo)) { VisualExceptionDialog.Show(new Exception($"Error trying to save file: {e.Message}", e)); } else { VisualExceptionDialog.Show(new Exception($"Error trying to save file \"{DownloadingTo}\": {e.Message}", e)); } } finally { _downloadData?.Close(); _fileStream?.Close(); } }