-1

I'm looking for how to get the name of the last file created in a folder. I work in .net framework 4.8.

With the following line of code I can get the name of all the files in the folder but I don't know how to sort them by creation date.

'System.IO.DirectoryInfo("c:\Parametre").GetFileSystemInfos()'

(I am using Aveva ArchestrA, which does not seem to be as flexible as Visual Studio as a development environment.)

Andrew Morton
  • 24,203
  • 9
  • 60
  • 84
Leo Bois
  • 1
  • 2
  • 2
    I suggest you research LINQ and the `OrderBy` method. – Jon Skeet Apr 19 '23 at 08:58
  • Not sure why you would call `GetFileSystemInfos` if you want files, given that it gets files and folders while `GetFiles` gets just files. – jmcilhinney Apr 19 '23 at 11:52
  • Assuming that you can't/won't use LINQ, `GetFiles` returns a `FileInfo` array and `Array.Sort` sorts an array. Seems a good place to start. – jmcilhinney Apr 19 '23 at 11:53

1 Answers1

2

You can make a variable to hold the latest date found and initialize it to the minimum value possible. Then you iterate over all the files and see if each one has a created date later than the date you've stored, and if so then you update the latest date and remember the filename, like this:

Dim dir As String = "C:\Parametre"

Dim latestFilename As String = ""
Dim latestDatetime As DateTime = DateTime.MinValue

Dim di As IO.DirectoryInfo = New System.IO.DirectoryInfo(dir)
For Each fi As IO.FileInfo In di.GetFiles()
    If fi.CreationTimeUtc > latestDatetime Then
        latestDatetime = fi.CreationTimeUtc
        latestFilename = fi.FullName
    End If
Next


' The variable latestFilename now contains the full name of
' the file with the latest creation date in the directory dir.

(Theoretically, although unlikely, there could be more than one file with the same latest creation timestamp, the above code will return only the first one that is recorded in the file system.)

Andrew Morton
  • 24,203
  • 9
  • 60
  • 84