Directory.GetFiles() in Modified Date/Time Order

I’ve been forced in to using vb.net for a windows service project which scans a folder of xml files, they need to be processed in order of the files modified date & time.  Directory.GetFiles returns an array of filenames in alphabetic order, I could find precious little information on the net so I thought I’d share what I came up with:-

Imports System.IO

Public Class clsCompareFileInfo

    Implements IComparer

    Public Function Compare(ByVal x As Object, ByVal y As Object) As Integer Implements IComparer.Compare

        Dim File1 As FileInfo

        Dim File2 As FileInfo

        File1 = DirectCast(x, FileInfo)

        File2 = DirectCast(y, FileInfo)

        Compare = DateTime.Compare(File1.LastWriteTime, File2.LastWriteTime)

    End Function

End Class

Then to use it…

Dim dirinfo As DirectoryInfo

Dim allFiles As FileInfo

dirinfo = New DirectoryInfo(sSelPath)

allFiles = dirinfo.GetFiles("*.xml")

Array.Sort(allFiles, New clsCompareFileInfo)

For Each fl As FileInfo In allFiles

    MessageBox(fl.FullName.ToString)

Next

To give credit where it’s really due I found the solution in c# at. I just converted the source from c# to vb.net.

This article is part of the GWB Archives. Original Author: Neil Smith

New on Geeks with Blogs

  • We Won The One Award I Actually Care About

    Full Scale made the Inc. 5000 for the fifth year straight, the 12th listing across my three companies. Here is why the one award you cannot buy is worth stopping for.

  • Your Customers Build the Features Now

    I let a tool I liked sit dead for a year rather than build the features I wanted. An MCP server meant I never had to, and your customers can do the same to your product.

  • Get the Size of a Directory in Linux the Easy Way

    du -sh for the quick answer, ncdu for the cleanup, df for the disk itself: every command for checking directory size in Linux, plus why du and df never agree.

  • Vim Search and Replace: The Ultimate Guide

    One :%s command replaces every match in a file before a find dialog would even open. The Vim substitute patterns worth the muscle memory: flags, ranges, capture groups, and multi-file edits.