Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 53
- private async void btnDownload_Click(object sender, RoutedEventArgs e)
- {
- DownloadBookAsync(file_url);
- }
- private async void DownloadBookAsync(String url)
- {
- cts = new CancellationTokenSource();
- Problem fileDownloaded = await DownloadFileFromWeb(url, cts.Token);
- switch (fileDownloaded)
- {
- case Problem.Ok:
- MessageBox.Show("OK");
- break;
- case Problem.Cancelled:
- MessageBox.Show("Canceled");
- break;
- case Problem.Other:
- default:
- MessageBox.Show("Other problem with download");
- break;
- }
- }
- // first define Cancellation Token Source - I've made it global so that CancelButton has acces to it
- public CancellationTokenSource cts = new CancellationTokenSource();
- public enum Problem { Ok, Cancelled, Other }; // results of my Task
- // the main method - I've described it a little below in the text
- public async Task<Problem> DownloadFileFromWeb(string item, CancellationToken cToken)
- {
- try
- {
- //get zipfile data
- using (Stream response_stream = await DownloadHpubFile(new Uri(item)))
- using (IsolatedStorageFile file = IsolatedStorageFile.GetUserStoreForApplication())
- {
- //Save zipfile data
- if (!file.DirectoryExists("FolderRoor/Files"))
- {
- file.CreateDirectory("FolderRoor/Files");
- }
- string dir = "/FolderRoor/Files/" + item.Trim();
- using (IsolatedStorageFileStream stream = new IsolatedStorageFileStream(dir, System.IO.FileMode.OpenOrCreate, FileAccess.ReadWrite, file))
- {
- byte[] buffer = new byte[1024];
- while (response_stream.Read(buffer, 0, buffer.Length) > 0) //Getting exception here now
- {
- stream.Write(buffer, 0, buffer.Length);
- }
- }
- }
- return Problem.Ok;
- }
- catch (Exception exc)
- {
- if (exc is OperationCanceledException)
- return Problem.Cancelled;
- else return Problem.Other;
- }
- }
- public static Task<Stream> DownloadHpubFile(Uri url)
- {
- var tcs = new TaskCompletionSource<Stream>();
- hpubDownloader = new WebClient();
- hpubDownloader.AllowReadStreamBuffering = false;
- hpubDownloader.OpenReadCompleted += (s, e) =>
- {
- if (e.Cancelled) tcs.TrySetCanceled();
- else if (e.Error != null) tcs.TrySetException(e.Error);
- else tcs.TrySetResult(e.Result);
- };
- hpubDownloader.DownloadProgressChanged += (s, e) =>
- {
- int value = e.ProgressPercentage;
- labelProgress.COntent=value;//show progress text of download as %
- };
- hpubDownloader.OpenReadAsync(url);
- return tcs.Task;
- }
- private void btnCancel_Click(object sender,EventArgs e)
- {
- if (hpubDownloader.IsBusy)
- {
- hpubDownloader.CancelAsync();
- if (this.cts != null)
- this.cts.Cancel();
- }
- else if (UnzipBook != null && UnzipBook.IsBusy)
- {
- UnzipBook.CancelAsync();
- }
- }
Add Comment
Please, Sign In to add comment