在Windows Metro App中下载并保存文件

时间:2014-08-20 17:43:04

标签: c# windows visual-studio windows-runtime microsoft-metro

我有一个C#,它从互联网上下载文件,保存,打开并阅读并复制它们。

代码看起来像这样

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);

但WebClient,File,Debug.Print,DownloadProgressChangedEventHandler,DownloadProgressChangedEventArgs等内容似乎在Windows Metro App中不可用。

那么,我如何在Windows Metro App中实现相同的功能呢?

是否有可用的移植指南?

1 个答案:

答案 0 :(得分:1)

localFolder商店用于特定于应用的存储空间。然后,您可以使用StorageFileFileIOCachedFileManager类来帮助您。此外,在运行异步方法时使用await关键字。

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();
}