Sebastian
Sebastian

Reputation: 4811

Download and save a picture from a url Universal windows app

I am using the below code to downlaod the picture form a remote url and save to Local storage folder

        try
        {
            var rootFolder = await ApplicationData.Current.LocalFolder.CreateFolderAsync( "MyAppName\\CoverPics", CreationCollisionOption.OpenIfExists);

            var coverpic_file = await rootFolder.CreateFileAsync(filename, CreationCollisionOption.FailIfExists);
            try
            {
                var httpWebRequest = HttpWebRequest.CreateHttp(coverUrl);
                HttpWebResponse response = (HttpWebResponse)await httpWebRequest.GetResponseAsync();
                Stream resStream = response.GetResponseStream();
                using (var stream = await coverpic_file.OpenAsync(FileAccessMode.ReadWrite))
                {
                    await resStream.CopyToAsync(stream.AsStreamForWrite());
                }
                response.Dispose();
            }
            catch //any exceptions happend while saving the picture
            {
                saved = false;
            }
        }
        catch
        {
            //https://msdn.microsoft.com/en-us/library/windows/apps/br227250.aspx 
            //Raise an exception if file already present 
            saved = true;
        }

This code is working for me in most of the cases , but i noticed that for few pictures the image is not downloading completely.

I am callling this function in an async block for more tahn 100 images in a single go inside the foreach loop and in the end few of them are failed downloads

[ Either i can see some invalid file is getting created

or part of image only in downloading and rest of the area i can see a black colour block [ looks like image is corrupted].

Size of all images is less than 1 MB only

Can some one help me to optimize this code or point out the mistake in code so i can able to download all the images completely

Upvotes: 4

Views: 9079

Answers (3)

sonicbabbler
sonicbabbler

Reputation: 851

I tried your download and experienced the same issues.

var myFolder = await ApplicationData.Current.LocalFolder.CreateFolderAsync("MyFolderPath", CreationCollisionOption.OpenIfExists);
var myFile = await myFolder.CreateFileAsync(fileName, CreationCollisionOption.ReplaceExisting);

BackgroundDownloader downloader = new BackgroundDownloader();
DownloadOperation download = downloader.CreateDownload(new Uri(URL), myFile);
await download.StartAsync();

Upvotes: 0

Sebastian
Sebastian

Reputation: 4811

I am not seeing any error in my code. But after trying some different ways of downloading and saving a file my code looks like this and

 try
            {
                HttpClient client = new HttpClient(); // Create HttpClient
                byte[] buffer = await client.GetByteArrayAsync(coverUrl); // Download file
                using (Stream stream = await coverpic_file.OpenStreamForWriteAsync())
                    stream.Write(buffer, 0, buffer.Length); // Save
            }
            catch
            {
                saved = false;
            }

And this code is working fine without causing any issues All images are downloading completely and no more issues of black block on images.

If any one can points out the difference with my first code will be really helpful to understood the reason for error

Upvotes: 6

Ask Too Much
Ask Too Much

Reputation: 637

Have you tried using new Windows.Web.Http.HttpClient instead of HttpWebRequest?

Also take a look this SO question : How do I use the new HttpClient from Windows.Web.Http to download an image?

If you not familiar with HttpClient, I sugest to watch CH9 presentation : https://channel9.msdn.com/Events/Build/2013/4-092

Upvotes: 1

Related Questions