Downloading an image from url does not always save the entire image (Winrt)

I use the following code to download an image from a url

HttpClient client = new HttpClient(); var stream = await client.GetStreamAsync(new Uri("<your url>")); var file = await KnownFolders.PictureLibrary.CreateFileAsync("myfile.png"); using (var targetStream = await file.OpenAsync(FileAccessMode.ReadWrite)) { using (stream) await stream.CopyToAsync(targetStream.AsStreamForWrite()); } 

several users reported that it does not always download the entire image. The fact that they sometimes get partial images, and the rest is just rubbish.

Is there a reason for this? Thanks!

+7
source share
3 answers

I would suggest trying the WebClient class using the DownloadData or DownloadDataAsync method.

 File.WriteAllBytes("myfile.png", new WebClient().DownloadData("<your url>")); 

edit If the stream creates problems, you can use the response of the byte array. Your using statement with asynchronous code inside may call it earlier, maybe?

 var httpClient = new HttpClient(); var data = await httpClient.GetByteArrayAsync(new Uri("<Your URI>")); var file = await KnownFolders.PictureLibrary.CreateFileAsync("myfile.png"); var targetStream = await file.OpenAsync(FileAccessMode.ReadWrite) await targetStream.AsStreamForWrite().WriteAsync(data, 0, data.Length); targetStream.FlushAsync().Wait(); targetStream.Close(); 
+7
source

BackgroundDownloader is the easiest way to download a file.

 using Windows.Storage; public async Task DownloadPhoto(Uri uri) { var folder = ApplicationData.Current.LocalFolder; var photoFile = await folder.CreateFileAsync("photo.jpg", CreationCollisionOption.ReplaceExisting); var downloader = new Windows.Networking.BackgroundTransfer.BackgroundDownloader(); var dl = downloader.CreateDownload(uri, photoFile); await dl.StartAsync(); } 
+2
source

If you use HttpClient, if your image is larger than 64K, it will fail. You will need to set something more for httpClient.MaxResponseContentBufferSize.

See “MSDN Quick Beginnings” for a maximum buffer size of 256 KB. http://msdn.microsoft.com/en-us/library/windows/apps/xaml/JJ152726(v=win.10).aspx

Personally, I use BackgroundDownloader.

+1
source

All Articles