Comparing FileInfo Created Dates

dotnetnube

Member
Joined
Aug 20, 2008
Messages
8
Programming Experience
Beginner
I need to find the newest file in a file folder by looking at the creation date. What is the best way to go about this?

I already have the code below to do some other work. Can I insert code to do the comparison inside the For...Each, or is there a better way to do it?

Dim sourceFiles As FileInfo()
Dim sourceFile As FileInfo

For each sourceFile in Sourcefiles
...existing code
Next


Thank you in advance!
 
Sort the array by one of the file date properties, this can be done with a Comparison(Of T) delegate:
VB.NET:
Array.Sort(infos, AddressOf FileDateSort)
Where the FileDateSort implementation can be this:
VB.NET:
Function FileDateSort(ByVal x As IO.FileInfo, ByVal y As IO.FileInfo) As Integer
    Return x.LastWriteTime.CompareTo(y.LastWriteTime)
End Function
Now the FileInfo array is sorted from old to new, where last item is the most recent file.

If you have to do a full For-Each loop anyway then you can save a little processing time by using a temp variable and compare each FileInfo to find the newest file:
VB.NET:
Dim temp As IO.FileInfo = infos(0)
For Each info As IO.FileInfo In infos
    If temp.LastWriteTime < info.LastWriteTime Then
        temp = info
    End If
Next
At the end of the loop the temp variable hold the info for newest file.
 
Back
Top