Modern mobile apps require us to continuously update the app contents when we are online and read the last downloaded content from phone storage when we are offline. Given below is a code snippet which will download a file from Internet and save it in IsolatedStorage.
Declare
public enum Problem { Ok, Cancelled, Other };
Function
public async Task DownloadFileFromWeb(Uri uriToDownload, string fileName, CancellationToken cToken)
{
Problem prob;
try
{
using (Stream mystr = await DownloadFile(uriToDownload))
using (IsolatedStorageFile ISF = IsolatedStorageFile.GetUserStoreForApplication())
{
if (ISF.FileExists(fileName))
{
ISF.DeleteFile(fileName);
}
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);
}
}
}
prob = Problem.Ok;
}
catch (Exception exc)
{
if (exc is OperationCanceledException)
prob= Problem.Cancelled;
else
prob= Problem.Other;
}
return prob;
}
public static Task DownloadFile(Uri url)
{
var tcs = new TaskCompletionSource();
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;
}