VB.Net - shortcut to obtaining most recent file

Member_2_7964482
Member_2_7964482 used Ask the Experts™
on
Trying to find the most recent file with the following code:

 Dim FileList = New DirectoryInfo(SummaryDir).GetFiles(Fin + "*.xls").OrderByDescending(Function(x) x.CreationTime)
        For Each f As FileInfo In FileList
            lastfile = f.Name
            Exit For
        Next

Is there a way to avoid the for/next to obtain the last filename?
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Senior .Net Consultant
Top Expert 2016
Commented:
sure. you can use FirstOrDefault like this:

MessageBox.Show(New DirectoryInfo("C:\temp").GetFiles("*.tmp").OrderByDescending(Function(x) x.CreationTime).FirstOrDefault().Name)

Open in new window

Top Expert 2016

Commented:
HI,

maybe

        Dim fi As New New DirectoryInfo(SummaryDir)
        Dim files = fi.GetFiles(Fin + "*.xls").ToList
        Dim last = (From file In files Select file Order By file.CreationTime Descending).FirstOrDefault

Open in new window

Regards

Author

Commented:
Perfect solution.  Thank you

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial