简体   繁体   English

在Windows应用商店中下载文件

[英]Downloading a file in Windows store app

I am having trouble downloading files through my windows store app. 我无法通过我的Windows应用商店下载文件。 Here is my method for downloading: 这是我的下载方法:

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

    }

On the marked line i get this exception: 在标记的行上我得到这个例外:

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.

What might be causing this? 可能是什么导致了这个?

You're calling GetResults on an IAsyncOperation that has not yet completed, and so is not in a state where you can access the results (because they do not exist yet). 您正在对尚未完成的IAsyncOperation调用GetResults,因此不能处于可以访问结果的状态(因为它们尚不存在)。

In fact, you don't need the call to GetResults at all, you just need: 事实上,您根本不需要调用GetResults,您只需要:

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

Changing 更改

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

to

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

seems to fix the problem, though i don't know why 似乎解决了这个问题,虽然我不知道为什么

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM