Sunday, May 25, 2014

How to get Latest Modified or Created file in Directory ( A recursive search method)

Today I want to share little knowledge that how we can get the latest file in different folder with same name.
For example we have text file with name employee ID + extension (.txt) in different folders may be department wise or deputation wise. Now the task is how to get the latest file of an employee from different folder.
Here is the function that gives you the file.
You must import ( Using (C#) the following assemblies:

Imports System.IO
Imports System.Linq

Now call the function and passed it employee id and root directory.
Private Function GetLatestFile(ByVal EmpId As String, ByVal rootDirectory As String) As String
        ''Get Direcotry list order by CreateTime Desc
        Dim strPath As String = String.Empty
        Dim directories As IEnumerable(Of DirectoryInfo) = From path In System.IO.Directory.GetDirectories(rootDirectory) Let directory = New System.IO.DirectoryInfo(path) Order By directory.LastAccessTime Descending Select directory
        If directories IsNot Nothing Then
            For Each drIno As DirectoryInfo In directories
                If File.Exists(drIno.FullName + "\" + EmpId + ".txt") Then
                    strPath = drIno.FullName + "\" + EmpId + ".txt"
                    Exit For
                End If
        End If
        Return strPath

    End Function

Search This Blog