avb
avb

Reputation: 1751

Download and save a file in Windows Metro App

I have an C# which downloads files from the internet, saves them, open and read them and copy them.

The code looks something like this

private static void DownloadSpec()
{
    Debug.Print("Downloading Spec...");
    WebClient webClient = new WebClient();
    webClient.DownloadFileCompleted += new AsyncCompletedEventHandler(CompletedSpec);
    webClient.DownloadProgressChanged += new DownloadProgressChangedEventHandler(ProgressChanged);
    webClient.DownloadFileAsync(new Uri("http://myurl.ul/spec"), @"spec");
}

...
...
...
isNewSpecPresent = File.Exists(@"spec");
...
...
file = new System.IO.StreamReader(@"./download/spec");
...
...
File.Copy(@"spec", @"./download/spec", true);

But things like WebClient, File, Debug.Print, DownloadProgressChangedEventHandler, DownloadProgressChangedEventArgs seems to be not available in a Windows Metro App.

So, how can I achieve the same thing in a Windows Metro App?

Is there a porting guide available?

Upvotes: 0

Views: 800

Answers (1)

Cam Bruce
Cam Bruce

Reputation: 5689

Use the localFolder store for app specific storage. Then you can use the StorageFile, FileIO, and CachedFileManager classes to help you out. Also, use the await keyword when running async methods.

var response = await httpClient.GetAsync(url);
var result = await response.Content.ReadAsStringAsync();

var localFolder = Windows.Storage.ApplicationData.Current.LocalFolder;
StorageFile file = await localFolder.CreateFileAsync("dataFile.txt", 
   CreateCollisionOption.ReplaceExisting);

await FileIO.WriteTextAsync(file, result);

var status = await CachedFileManager.CompleteUpdatesAsync(file);

if (status == FileUpdateStatus.Complete)
{
    var md = new MessageDialog("done");

    IUICommand x = await md.ShowAsync();
}

Upvotes: 1

Related Questions