I am trying to download and save a file in the isolated storage. This is my attempt of downloading the file
Task.Run(async () => { await DownloadFileFromWeb(new Uri(@"http://main.get4mobile.net/ringtone/ringtone/ibMjbqEYMHUnso8MErZ_UQ/1452584693/fa1b23bb5e35c8aed96b1a5aba43df3d/stefano_gambarelli_feat_pochill-land_on_mars_v2.mp3"), "mymp3.mp3"); }).Wait();
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;
}
public static async Task<Problem> DownloadFileFromWeb(Uri uriToDownload, string fileName)
{
using (Stream mystr = await DownloadFile(uriToDownload))
using (IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication())
{
using (IsolatedStorageFileStream file = new IsolatedStorageFileStream(fileName, FileMode.OpenOrCreate, isf))
{
using (var fs = new StreamWriter(file))
{
byte[] bytesInStream = new byte[mystr.Length];
mystr.Read(bytesInStream, 0, (int)bytesInStream.Length);
file.Write(bytesInStream, 0, bytesInStream.Length);
file.Flush();
}
}
}
return Problem.Ok;
}
Obviously I am doing something wrong here since the file is never and the app is stack forever after the call. However I believe I am not far from getting there.
Any help is greatly appreciated.
Add this methid and call it from there, it should work.
Downlaod_Click()
public static async void Downlaod_Click()
{
var cts = new CancellationTokenSource();
Problem fileDownloaded = await MainHelper.DownloadFileFromWeb(new Uri(@"url", UriKind.Absolute), "myfile.mp3", 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;
}
}