How can I add the file creation date filter for files created today and tomorrow?
This part don't work and i need to add files created today and tomorrow
.Where(Function(file) New FileInfo(file).CreationTime.Date = DateTime.Today.Date)
Dim pdfList As String() = Directory.GetFiles(sourceDir, "*.PDF").Where(Function(file) New FileInfo(file).CreationTime.Date = DateTime.Today.Date)
For Each f As String In pdfList
'Remove path from the file name.
Dim fName As String = f.Substring(sourceDir.Length 1)
' Use the Path.Combine method to safely append the file name to the path.
' Will overwrite if the destination file already exists.
File.Copy(Path.Combine(sourceDir, fName), Path.Combine(backupDir, fName), True)
Next
CodePudding user response:
Dim folder As New DirectoryInfo(sourceFolderPath)
Dim files = folder.EnumerateFiles("*.pdf").Where(Function(fi) fi.CreationTime.Date = Date.Today)
For Each file In files
file.CopyTo(Path.Combine(backupFolderPath, file.Name))
Next
There are a few things to note here:
- We are creating a
DirectoryInfo
and using it to getFileInfo
objects. Given that you were creating aFileInfo
for each file anyway, it's silly not to do this. ThatFileInfo
object gives you the creation time, file name without the folder path and a method to copy the file. - We are calling
EnumerateFiles
rather thanGetFiles
. The latter returns an array containing all files, but we don't want all files in this case. If you're going to filter then enumeration is better, because it gets each file one by one, processes a file and discards it before getting the next. That's more efficient. In this case, we don't even callToArray
orToList
, so the files aren't actually retrieved until the loop and then they are retrieved and processed one by one. - The is no point using
Date.Today.Date
.Today
has already had the time zeroed. Internally,Date.Today
usesDate.Now.Date
.