简体   繁体   中英

Downloading a file in Windows store app

I am having trouble downloading files through my windows store app. 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).

In fact, you don't need the call to GetResults at all, you just need:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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