Jimmu John Jimmu John - 4 months ago 64
Vb.net Question

Get files in the last month using directory.enumerate files?

I'm getting a list of files from my folder using directory.enumerate files. I want to only get the files created within the last month to the current date. Currently I can only get the first 100 or so files but want to do so with a date.

Dim orderedByCreation = From file In Directory.EnumerateFiles(FilePath, "*.xlsm")
Let createdAt = System.IO.File.GetCreationTime(file)
Order By createdAt Descending
Select file

Dim mylist = orderedByCreation.Take(100)

>>>> Want to get files within the last month here before adding to grid.

For Each filePath As String In mylist
Dim fileNameOnly As String = Path.GetFileNameWithoutExtension(filePath.ToString())
Dim fileCreatedDate As DateTime = File.GetCreationTime(filePath.ToString())
Dim dt As DateTime = File.GetLastAccessTime(filePath.ToString())

Grid.Rows.Add(fileNameOnly, fileCreatedDate, dt)


Next

Answer

Change your query to

Dim orderedByCreation = From file In  Directory.EnumerateFiles(FilePath, "*.xlsm")
     Let createdAt = System.IO.File.GetCreationTime(file)
     Where createdAT >= DateTime.Today.AddMonths(-1).Date
     Order By createdAt Descending
     Select file

By the way, given the fact that you need some other info about your file you could consider to use a DirectoryInfo.EnumerateFiles to get back a list of FileInfo instances that have also information LastAccessTime

Dim di = New DirectoryInfo(FilePath)
Dim orderedByCreation = From file In di.EnumerateFiles("*.xslm")
                        Where file.CreationTime >= DateTime.Today.AddMonths(-1).Date
                        Order By file.CreationTime Descending
                        Select file

For Each fi In orderedByCreation.Take(100)
    Dim fileNameOnly As String = Path.GetFileNameWithoutExtension(fi.Name)
    Dim fileCreatedDate As DateTime = fi.CreationTime
    Dim dt As DateTime = fi.LastAccessTime
    ....
Next

To exclude files that starts with a tilde

Dim orderedByCreation = From file In Directory.EnumerateFiles(FilePath, "*.xslm")
     Let createdAt = System.IO.File.GetCreationTime(file)
     Where createdAT >= DateTime.Today.AddMonths(-1).Date AndAlso
           Not Path.GetFilename(file).StartsWith("~")
     Order By createdAt Descending
     Select file
Comments