Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Downloading image from url doesn't always save the entire image (Winrt)

I'm using 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 have reported that it doesn't always download the entire image. That they sometimes get partial images and the rest is just garbage.

Is there any reason for this? Thanks!

like image 706
Smeegs Avatar asked Mar 11 '13 14:03

Smeegs


3 Answers

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

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

edit If the stream is giving you trouble you could use the byte array response instead. Your "using" statement with async code inside may be causing it to dispose early, perhaps?

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();
like image 56
Louis Ricci Avatar answered Nov 05 '22 03:11

Louis Ricci


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();
}
like image 23
akhansari Avatar answered Nov 05 '22 02:11

akhansari


If your using HttpClient then if your image is larger than 64K it will error out. You will have to set the httpClient.MaxResponseContentBufferSize to something larger.

See the MSDN Quick Start where they set the max-buffer-size to 256K. http://msdn.microsoft.com/en-us/library/windows/apps/xaml/JJ152726(v=win.10).aspx

Personally though, I use the BackgroundDownloader.

like image 44
MudRider Avatar answered Nov 05 '22 02:11

MudRider