在Windows商店应用中下载文件

3

我在使用Windows Store应用下载文件时遇到了问题。以下是我的下载方法:

private static async void DownloadImage()
    {
        HttpClient client = new HttpClient();

        HttpResponseMessage message = await client.GetAsync("http://coolvibe.com/wp-content/uploads/2010/05/scifiwallpaper1.jpg");

        StorageFolder myfolder = Windows.Storage.ApplicationData.Current.LocalFolder;
        StorageFile sampleFile = myfolder.CreateFileAsync("image.jpg", CreationCollisionOption.ReplaceExisting).GetResults();// this line throws an exception
        byte[] file = await message.Content.ReadAsByteArrayAsync();

        await FileIO.WriteBytesAsync(sampleFile, file);
        var files = await myfolder.GetFilesAsync();

    }

在标记的行上,我遇到了这个异常:
An exception of type 'System.InvalidOperationException' occurred in ListStalkerWin8.exe but was not handled in user code

WinRT information: A method was called at an unexpected time.

Additional information: A method was called at an unexpected time.

可能是什么原因导致这种情况发生?
2个回答

2
您正在调用尚未完成的IAsyncOperation上的GetResults,因此它不处于可以访问结果的状态(因为结果尚不存在)。
实际上,您根本不需要调用GetResults,您只需要:
StorageFile sampleFile = await myfolder.CreateFileAsync("image.jpg", CreationCollisionOption.ReplaceExisting);

非常感谢Mario Stoilov和Chris W. 我一直在为这个问题苦恼。 - FebinDonz

0

更改

StorageFile sampleFile = myfolder.CreateFileAsync("image.jpg", CreationCollisionOption.ReplaceExisting).GetResults();//

StorageFile sampleFile = await myfolder.CreateFileAsync("image.jpg", CreationCollisionOption.ReplaceExisting);

看起来解决了问题,但我不知道为什么


它修复了问题,因为CreateFileAsync()函数是异步的。在Windows Store C# API中(我不知道WinJS),任何异步函数都会有“Async”后缀。这意味着您可以启动文件创建,做其他事情,然后在创建后稍后检索StorageFile。通过添加“await”关键字,您使函数同步化;就像说“启动文件创建并等待直到完成”。我知道它很长,但请查看http://msdn.microsoft.com/en-us/library/vstudio/hh191443.aspx?cs-save-lang=1&cs-lang=csharp#code-snippet-1 - YasharBahman

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接