1

I have a PictureBox in .Net that displays images from a folder "Photos" using the following code on a click event:

PictureBox1.Image = Nothing 'Clearing PictureBox1 
Dim bmPhotos as new Bitmap("C:\Photos\ImageName.gif")
PictureBox1.Image = bmPhotos

I want to replace "ImageName" in the file path with the name of the last captured image programatically. Is there a way to find out the name of the image that was added last to the "Photos" folder?

Thank you.

Reza Aghaei
  • 120,393
  • 18
  • 203
  • 398
Alc
  • 35
  • 1
  • 6
  • Have a look at http://stackoverflow.com/questions/1179970/how-to-find-the-most-recent-file-in-a-directory-using-net-and-without-looping Probably that's what you are looking for. – serhiyb Jan 14 '16 at 00:56

1 Answers1

0

If the last created file is what you need, you can find it this way:

Dim file = System.IO.Directory.GetFiles("path") _
                 .OrderByDescending(Function(f) New System.IO.FileInfo(f).CreationTime) _
                 .FirstOrDefault()

You can also use GetFiles("path", "*.gif") to limit the result between gif files.

Also you can add some criteria after GetFiles, to limit the file types to be between specific file types, for example:

.Where(Function(f) New String() {".gif", ".png"}.Contains(System.IO.Path.GetExtension(f)))

Then you can show the image this way:

Me.PictureBox1.ImageLocation = file

Or

Me.PictureBox1.Load(file)
Reza Aghaei
  • 120,393
  • 18
  • 203
  • 398
  • Amazing!!! Thank you very much. I tried your code and it worked. I am wondering if there is a way to populate PictureBox1 automatically as soon as an image is added to the folder without me having to click a button to activate the code? Thank you once a gain. – Alc Jan 14 '16 at 19:52
  • You are welcome :) To do it automatically, you can use [`FileSystemWatcher`](https://msdn.microsoft.com/en-us/library/system.io.filesystemwatcher(v=vs.110).aspx). The msdn link shares good information about how to use FileSystemWatcher`. You can also ask your question about using `FileSystemWatcher` in a new post :) – Reza Aghaei Jan 14 '16 at 22:07