Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.ComponentModel;
- using System.IO;
- using System.Net;
- using System.Threading.Tasks;
- using System.Windows.Forms;
- namespace WindowsFormsApplication1
- {
- class Installer
- {
- Button saveButton;
- ProgressBar progressBar;
- Label statusLabel;
- Boolean downloadDone;
- public Installer(Button _saveButton, ProgressBar _progressBar, Label _statusLabel)
- {
- saveButton = _saveButton;
- progressBar = _progressBar;
- statusLabel = _statusLabel;
- }
- public async void Start(string fileUrl)
- {
- saveButton.BeginInvoke((Action)(() => {
- saveButton.Enabled = false;
- }));
- Task<bool> downloadArchiveTask = DownloadArchiveAsync(fileUrl);
- bool downloadArchiveDone = await downloadArchiveTask;
- if (downloadArchiveDone)
- statusLabel.BeginInvoke((Action)(() => {
- statusLabel.Text = "Download Completed";
- }));
- }
- async Task<bool> DownloadArchiveAsync(string fileUrl)
- {
- var downloadLink = new Uri(fileUrl);
- var saveFilename = Path.GetFileName(downloadLink.AbsolutePath);
- DownloadProgressChangedEventHandler DownloadProgressChangedEvent = (s, e) =>
- {
- progressBar.BeginInvoke((Action)(() => {
- progressBar.Value = e.ProgressPercentage;
- }));
- var downloadProgress = string.Format("{0} MB / {1} MB",
- (e.BytesReceived / 1024d / 1024d).ToString("0.00"),
- (e.TotalBytesToReceive / 1024d / 1024d).ToString("0.00"));
- statusLabel.BeginInvoke((Action)(() => {
- statusLabel.Text = "Downloading " + downloadProgress + " ...";
- }));
- };
- AsyncCompletedEventHandler AsyncCompletedEvent = (s, e) =>
- {
- // Todo: Extract
- downloadDone = true;
- };
- using (WebClient webClient = new WebClient())
- {
- webClient.DownloadProgressChanged += DownloadProgressChangedEvent;
- webClient.DownloadFileCompleted += AsyncCompletedEvent;
- webClient.DownloadFileAsync(downloadLink, saveFilename);
- }
- await IsDownloadDone();
- return true;
- }
- async Task IsDownloadDone()
- {
- await Task.Run(() =>
- {
- while (!downloadDone) ;
- });
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement