Download a file in a Windows Store app

I'm having trouble downloading files through the Windows storage application. Here is my download method:

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

In 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 could be the reason for this?

+4
source share
2 answers

You call GetResults on an IAsyncOperation, which is not yet completed, and therefore not in a state where you can access the results (because they do not exist yet).

Actually, you don't need a GetResults call at all, you just need:

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

The change

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

to

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

seems to fix the problem although I don't know why

0
source

Source: https://habr.com/ru/post/1495918/


All Articles