Download and save an Async file on Windows Phone 8

How to download and save the file IsolatedStorageasynchronously? At first I used it WebClientfor this purpose, but I could not wait for the completion, so I found useful code here here .

However, this is also not in full format. I found a function:

public static Task<Stream> DownloadFile(Uri url)
{
    var tcs = new TaskCompletionSource<Stream>();
    var wc = new WebClient();
    wc.OpenReadCompleted += (s, e) =>
    {
        if (e.Error != null) tcs.TrySetException(e.Error);
        else if (e.Cancelled) tcs.TrySetCanceled();
        else tcs.TrySetResult(e.Result);
    };
    wc.OpenReadAsync(url);
    return tcs.Task;
}

But how to save this file to IsolatedStorage? Someone will help me fulfill this function!

+4
source share
3 answers

This that har07 is published should work. If you need to expand your method a bit, I would try to do something like this (although it has not been tested, but should work):

( - )

// first define Cancellation Token Source - I've made it global so that CancelButton has acces to it
CancellationTokenSource cts = new CancellationTokenSource();
enum Problem { Ok, Cancelled, Other }; // results of my Task

// cancelling button event
private void CancellButton_Click(object sender, RoutedEventArgs e)
{
   if (this.cts != null)
        this.cts.Cancel();
}

// the main method - I've described it a little below in the text
public async Task<Problem> DownloadFileFromWeb(Uri uriToDownload, string fileName, CancellationToken cToken)
{
   try
   {
       using (Stream mystr = await DownloadFile(uriToDownload))
           using (IsolatedStorageFile ISF = IsolatedStorageFile.GetUserStoreForApplication())
           {
           if (ISF.FileExists(fileName)) return Problem.Other;
           using (IsolatedStorageFileStream file = ISF.CreateFile(fileName))
           {
               const int BUFFER_SIZE = 1024;
               byte[] buf = new byte[BUFFER_SIZE];

               int bytesread = 0;
               while ((bytesread = await mystr.ReadAsync(buf, 0, BUFFER_SIZE)) > 0)
               {
                  cToken.ThrowIfCancellationRequested();
                  file.Write(buf, 0, bytesread);
               }
           }
       }
       return Problem.Ok;
    }
    catch (Exception exc)
    {
       if (exc is OperationCanceledException)
           return Problem.Cancelled;
       else return Problem.Other; 
    }
}

// and download
private async void Downlaod_Click(object sender, RoutedEventArgs e)
{
   cts = new CancellationTokenSource();
   Problem fileDownloaded = await DownloadFileFromWeb(new Uri(@"http://filedress/myfile.txt", UriKind.Absolute), "myfile.txt", cts.Token);
   switch(fileDownloaded)
   {
      case Problem.Ok:
           MessageBox.Show("File downloaded");
           break;
      case Problem.Cancelled:
           MessageBox.Show("Download cancelled");
           break;
      case Problem.Other:
      default:
           MessageBox.Show("Other problem with download");
           break;
    }
}

- , Button.Click . , DownloadFile (uriToDownload) , OperationCancelled - .

, .

+3

- ( ):

try
{
    using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
    {
        IsolatedStorageFileStream fileStream = myIsolatedStorage.CreateFile("fileNameHere");

        BitmapImage bitmap = new BitmapImage();
        var stream = await DownloadFile(new Uri("http://someuri.com", UriKind.Absolute));
        bitmap.SetSource(stream);
        WriteableBitmap wb = new WriteableBitmap(bitmap);

        // Encode WriteableBitmap object to a JPEG stream.
        Extensions.SaveJpeg(wb, fileStream, wb.PixelWidth, wb.PixelHeight, 0, 85);
        fileStream.Close();
    }
}
catch (Exception ex)
{
    //Exception handle appropriately for your app  
}

[]

+3

In my opinion, the best way to use a built-in implementation like this (Wrapping Begin / End asynchronous API):

var url = new Uri(UriString, UriKind.Absolute);
var fileName = Path.GetFileName(url.LocalPath);

var w = WebRequest.CreateHttp(url);
var response = await Task.Factory.FromAsync<WebResponse>(w.BeginGetResponse, w.EndGetResponse, null);
await response.GetResponseStream().CopyToAsync(new FileStream(ApplicationData.Current.LocalFolder.Path + @"\" + fileName, FileMode.CreateNew));
-1
source

Source: https://habr.com/ru/post/1525372/


All Articles