【问题标题】:How do I add the file creation date filter?如何添加文件创建日期过滤器?
【发布时间】:2021-11-06 22:42:47
【问题描述】:

如何为今天和明天创建的文件添加文件创建日期过滤器?

这部分不起作用,我需要添加今天和明天创建的文件:

.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

【问题讨论】:

  • A Date 值具有增加时间以在过去或将来获得另一个 Date 的方法,例如Date.Today.AddDays(1) 会给你明天的日期,Date.Today.AddDays(-1) 会给你昨天的日期。

标签: vb.net forms winforms filesystems


【解决方案1】:
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

这里有几点需要注意:

  1. 我们正在创建一个DirectoryInfo 并使用它来获取FileInfo 对象。鉴于您无论如何都要为每个文件创建一个FileInfo,所以不这样做是愚蠢的。 FileInfo 对象为您提供了创建时间、不带文件夹路径的文件名以及复制文件的方法。
  2. 我们打电话给EnumerateFiles,而不是GetFiles。后者返回一个包含所有文件的数组,但在这种情况下我们不希望所有文件。如果您要过滤,那么枚举会更好,因为它会一个接一个地获取每个文件,处理一个文件并在获取下一个文件之前将其丢弃。这样更有效率。在这种情况下,我们甚至不调用ToArrayToList,因此直到循环才真正检索文件,然后逐一检索和处理它们。
  3. 使用Date.Today.Date 是没有意义的。 Today 已经把时间归零了。在内部,Date.Today 使用 Date.Now.Date

【讨论】:

    猜你喜欢
    • 2022-06-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-08-08
    • 2020-04-27
    • 2021-02-10
    • 1970-01-01
    • 2021-08-15
    相关资源
    最近更新 更多