Jmat4119

Download code with cancelation support

Feb 10th, 2014
108
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 3.69 KB | None | 0 0
  1. 53
  2. private async void btnDownload_Click(object sender, RoutedEventArgs e)
  3. {
  4. DownloadBookAsync(file_url);
  5. }
  6.  
  7. private async void DownloadBookAsync(String url)
  8. {
  9. cts = new CancellationTokenSource();
  10. Problem fileDownloaded = await DownloadFileFromWeb(url, cts.Token);
  11. switch (fileDownloaded)
  12. {
  13. case Problem.Ok:
  14. MessageBox.Show("OK");
  15. break;
  16. case Problem.Cancelled:
  17. MessageBox.Show("Canceled");
  18. break;
  19. case Problem.Other:
  20. default:
  21. MessageBox.Show("Other problem with download");
  22. break;
  23. }
  24. }
  25.  
  26. // first define Cancellation Token Source - I've made it global so that CancelButton has acces to it
  27. public CancellationTokenSource cts = new CancellationTokenSource();
  28. public enum Problem { Ok, Cancelled, Other }; // results of my Task
  29. // the main method - I've described it a little below in the text
  30. public async Task<Problem> DownloadFileFromWeb(string item, CancellationToken cToken)
  31. {
  32. try
  33. {
  34. //get zipfile data
  35. using (Stream response_stream = await DownloadHpubFile(new Uri(item)))
  36. using (IsolatedStorageFile file = IsolatedStorageFile.GetUserStoreForApplication())
  37. {
  38. //Save zipfile data
  39. if (!file.DirectoryExists("FolderRoor/Files"))
  40. {
  41. file.CreateDirectory("FolderRoor/Files");
  42. }
  43. string dir = "/FolderRoor/Files/" + item.Trim();
  44. using (IsolatedStorageFileStream stream = new IsolatedStorageFileStream(dir, System.IO.FileMode.OpenOrCreate, FileAccess.ReadWrite, file))
  45. {
  46. byte[] buffer = new byte[1024];
  47. while (response_stream.Read(buffer, 0, buffer.Length) > 0) //Getting exception here now
  48. {
  49. stream.Write(buffer, 0, buffer.Length);
  50. }
  51. }
  52. }
  53. return Problem.Ok;
  54. }
  55. catch (Exception exc)
  56. {
  57. if (exc is OperationCanceledException)
  58. return Problem.Cancelled;
  59. else return Problem.Other;
  60. }
  61. }
  62.  
  63. public static Task<Stream> DownloadHpubFile(Uri url)
  64. {
  65. var tcs = new TaskCompletionSource<Stream>();
  66. hpubDownloader = new WebClient();
  67. hpubDownloader.AllowReadStreamBuffering = false;
  68. hpubDownloader.OpenReadCompleted += (s, e) =>
  69. {
  70. if (e.Cancelled) tcs.TrySetCanceled();
  71. else if (e.Error != null) tcs.TrySetException(e.Error);
  72. else tcs.TrySetResult(e.Result);
  73. };
  74. hpubDownloader.DownloadProgressChanged += (s, e) =>
  75. {
  76. int value = e.ProgressPercentage;
  77. labelProgress.COntent=value;//show progress text of download as %
  78. };
  79. hpubDownloader.OpenReadAsync(url);
  80. return tcs.Task;
  81. }
  82.  
  83. private void btnCancel_Click(object sender,EventArgs e)
  84. {
  85. if (hpubDownloader.IsBusy)
  86. {
  87. hpubDownloader.CancelAsync();
  88. if (this.cts != null)
  89. this.cts.Cancel();
  90. }
  91. else if (UnzipBook != null && UnzipBook.IsBusy)
  92. {
  93. UnzipBook.CancelAsync();
  94. }
  95. }
Add Comment
Please, Sign In to add comment