Frank Martin
Frank Martin

Reputation: 3441

How to list file(s) created today in a directory using VB.Net

I am using the following code to sort all files in directory in descending order and then checking if file creation date is today's date.

Can this be improved to include .Where() condition at the end to only include files that were created today?

Code

Dim orderedFiles = New System.IO.DirectoryInfo("C:\\MyFolder").GetFiles().OrderByDescending(Function(p) p.LastWriteTime)

Upvotes: 1

Views: 2948

Answers (1)

Vivek S.
Vivek S.

Reputation: 21905

Based on your code just use Where(Function(p) p.CreationTime.Date = Now.Date) in lieu of OrderByDescending(Function(p) p.LastWriteTime)

 Dim orderedFiles = New System.IO.DirectoryInfo("C:\MyFolder") _
                              .GetFiles() _
                              .Where(Function(p) p.CreationTime.Date = Now.Date)

or

Dim Dir As New DirectoryInfo("C:\MyFolder")
Dim FilesInDir As FileSystemInfo()
FilesInDir = Dir.GetFileSystemInfos
Dim my_file = FilesInDir.Where(Function(p) p.CreationTime.Date = Now.Date)
  • my_file stores collection of files that created today

    Dim file_name As String
    file_name = my_file(0).FullName ' file in 0th position or you can loop thorough my_file 
    
  • This will show you the file name with absolute path i.e C:\MyFolder\file.txt

Upvotes: 3

Related Questions