Home > OS >  How do I add the file creation date filter?
How do I add the file creation date filter?

Time:09-16

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:

  1. We are creating a DirectoryInfo and using it to get FileInfo objects. Given that you were creating a FileInfo for each file anyway, it's silly not to do this. That FileInfo object gives you the creation time, file name without the folder path and a method to copy the file.
  2. We are calling EnumerateFiles rather than GetFiles. 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 call ToArray or ToList, so the files aren't actually retrieved until the loop and then they are retrieved and processed one by one.
  3. The is no point using Date.Today.Date. Today has already had the time zeroed. Internally, Date.Today uses Date.Now.Date.
  • Related