在 Windows Phone 8 中异步下载和保存文件 [英] Downloading and saving a file Async in Windows Phone 8
问题描述
如何将文件异步下载并保存到 IsolatedStorage
?我首先使用 WebClient
来达到目的,但我不能等到完成,所以我找到了一些有用的代码 此处.
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 之后取消.另一方面,如果 await DownloadFile(uriToDownload) 被取消,它会自动抛出 OperationCancelled - 然后您捕获该异常并返回足够的结果.
我还没有运行该代码,但它可能会显示主要思想.
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屋!