-->

Sorting files from directoryinfo by date in asp.ne

2019-05-07 14:34发布

问题:

how can I sort (not filter) directoryinfo files by date (oldest to recent) ? I am using asp.net and visual studio 2008

回答1:

The same as @DaRKoN_ in vb.net:

Module Module1

    Sub Main()
        Dim orderedFiles = New System.IO.DirectoryInfo("c:\\").GetFiles().OrderBy(Function(x) x.CreationTime)
        For Each f As System.IO.FileInfo In orderedFiles
            Console.WriteLine(String.Format("{0,-15} {1,12}", f.Name, f.CreationTime.ToString))
        Next
    End Sub

End Module


回答2:

The GetFiles() method on the DirectoryInfo class returns an Array, which implements IEnumerable. So you can apply all the standard LINQ extension methods.

var orderedFiles = new System.IO.DirectoryInfo("path")
                       .GetFiles()
                       .OrderBy(x => x.CreationTime);

Edit: Just realised this is tagged with VB. Also see the comment by Jon on the OP re: existing answers.



回答3:

This was tagged vb (which is why I came across it.) I thought I would throw the vb answer up there.

    Dim sDir As String = HttpRuntime.AppDomainAppPath
    Dim oDirInfo As System.IO.DirectoryInfo
    Dim oInfo As System.IO.FileInfo

    oDirInfo = New System.IO.DirectoryInfo(sDir)

    oInfo = oDirInfo.GetFiles().OrderByDescending(Function(p) p.LastWriteTime).First()

    return oInfo.LastWriteTime