在Windows应用商店中下载文件

时间:2013-08-08 09:37:35

标签: c# download windows-store-apps

我无法通过Windows应用商店下载文件。这是我的下载方法:

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 个答案:

答案 0 :(得分:2)

您正在对尚未完成的IAsyncOperation调用GetResults,因此不能处于可以访问结果的状态(因为它们尚不存在)。

事实上,您根本不需要调用GetResults,只需要:

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

答案 1 :(得分:0)

更改

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

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

似乎解决了这个问题,虽然我不知道为什么