Mario Stoilov
Mario Stoilov

Reputation: 3447

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?

Upvotes: 3

Views: 3268

Answers (2)

ChrisW
ChrisW

Reputation: 36

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

Upvotes: 2

Mario Stoilov
Mario Stoilov

Reputation: 3447

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

Upvotes: 0

Related Questions