Search code examples
c#imagewinformswebclientmemorystream

How to download an image only if it's not existing already?


I am writing a program that displays usercontrols in a flowlayout panel. The user layout has images, which are downloaded by the program.

For speeding up, the program should check, if the image to download already exists at the download location. If it exists, it may not download it again.

I am using this code.

WebClient wcGreatest = new WebClient();
Uri url = client.GetImageUrl(client.Config.Images.PosterSizes.Last(), searchSerie.PosterPath);
byte[] imageData = wcGreatest.DownloadData(url);
MemoryStream stream = new MemoryStream(imageData);
seriePopular.btnSerie.Image = Image.FromStream(stream);    
stream.Close();

Solution

  • if (File.Exists(pathPoster + fileName))
                            {
                                seriePopular.btnSerie.Image = Image.FromFile(pathPoster + fileName);
                            }
                            else
                            {
                                Uri url = client.GetImageUrl(client.Config.Images.PosterSizes.Last(), searchSerie.PosterPath);
                                byte[] imageData = wcGreatest.DownloadData(url);
                                File.WriteAllBytes(pathPoster + fileName, imageData);
                                seriePopular.btnSerie.Image = Image.FromFile(pathPoster + fileName);
                            }