下载和保存文件异步在Windows Phone 8的 [英] Downloading and saving a file Async in Windows Phone 8

查看:89
本文介绍了下载和保存文件异步在Windows Phone 8的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我怎样才能下载并保存文件到 IsolatedStorage 异步?
我用 Web客户端第一为宗旨,但我不能等待,直到完成,所以我找到了一些有用的code <一个href=\"http://stackoverflow.com/questions/15880890/downloading-media-file-pro-grammatically-in-windows-phone-8\">here.

How can I download and save a file to IsolatedStorage asynchronously? I used WebClient first for the purpose, but I couldn't await till completion so I found some useful code here.

然而,这也是不完整的格式。我发现功能:

However, this is also not in complete format. I found the 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;
}

但我怎么能将该文件保存到 IsolatedStorage ?有人帮我完成这个功能!

But how can I save this file to IsolatedStorage? Someone help me to complete this functionality!

推荐答案

这有什么 har07 贴,应该工作。如果你需要扩展你的方法一点点,我会尝试做这样的事情(尽管它没有进行测试,但应工作):

This, what har07 posted, should work. In case you need to extend your method a little, I would try to do something like this (though it is not tested, but should work):

(评论重修后 - 与取消)

(Rebuilt after comment - with Cancellation)

// 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另一方面 - 那么你捕获该异常并返回结果充足


我还没有运行code,但它可能会显示主要的想法。

I've added Cancellation Token - it means that your download operation can be cancelled after Button.Click. On the other hand if await DownloadFile(uriToDownload) is Cancelled it automatically throws OperationCancelled - then you catch that exception and return adequate result.

I haven't run that code, but it may show the main idea.

这篇关于下载和保存文件异步在Windows Phone 8的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆