【问题标题】:Fill a ListBox with Excel files older than x month用 x 个月以前的 Excel 文件填充列表框
【发布时间】:2018-11-14 12:55:46
【问题描述】:

我正在制作一个 WinForm 项目,该项目向我显示所选文件夹的 x 个月之前的所有 Excel 文件。
我可以使用所有 Excel 文件填充ListBox(请参见下面的代码)。
在选择超过 x 个月的时间时,我没有成功。我想我应该使用LastWriteTime,但找不到如何使用它。

谁能帮我找到解决方案?

Private Sub ListFiles(ByVal folderPath As String)
    filesListBox.Items.Clear()

    Dim fileNames As String() =
        System.IO.Directory.GetFiles(folderPath,
            "*.xl*", System.IO.SearchOption.TopDirectoryOnly)

    For Each fileName As String In fileNames
        fileslistbox.Items.Add(fileName)
    Next
End Sub

【问题讨论】:

    标签: excel vb.net winforms


    【解决方案1】:

    文件创建时间/上次写入时间的信息由FileInfo 类返回,该类通过FileSystemInfo 类提供文件的创建时间、上次写入时间和上次访问时间。

    查看是否需要文件创建时间或上次写入时间,具体取决于您的要求。
    上次访问时间可能仅返回文件 Creation DateTime,具体取决于系统。

    一个例子,修改了ListFiles方法:
    我在方法中添加了一个参数,OlderThanMonths,用于指定文件应包含在列表中多长时间
    在这里,DateTime 引用是 LastWriteTime

    Private Sub ListFiles(ByVal folderPath As String, OlderThanMonths As Integer)
        filesListBox.Items.Clear()
    
        Dim fileNames As String() = Directory.GetFiles(folderPath, "*.xl*", SearchOption.TopDirectoryOnly)
    
        ListBox1.BeginUpdate()
        For Each fileName As String In fileNames
            Dim FIinfo As New FileInfo(fileName)
            If FIinfo.LastWriteTime.AddMonths(OlderThanMonths) <= Date.Now Then
                filesListBox.Items.Add(fileName)
            End If
        Next
        ListBox1.EndUpdate()
    End Sub
    

    或者使用 LINQ Where() 过滤器:

    Private Sub ListFiles(ByVal folderPath As String, OlderThanMonths As Integer)
        filesListBox.Items.Clear()
    
        filesListBox.Items.AddRange(
            Directory.GetFiles(folderPath, "*.xl*", SearchOption.TopDirectoryOnly).
                      Where(Function(f) New FileInfo(f).LastWriteTime.AddMonths(OlderThanMonths) <= Date.Now).
                      ToArray())
    End Sub
    

    【讨论】:

      【解决方案2】:

      你快到了。只需要添加一个 IF 子句来检查修改日期。

      检查此代码示例:

      Private Sub ListFiles(ByVal folderPath As String)
          filesListBox.Items.Clear()
      
          Dim fileNames As String() =
              System.IO.Directory.GetFiles(folderPath,
                  "*.xl*", System.IO.SearchOption.TopDirectoryOnly)
      
          For Each fileName As String In fileNames
              Dim dtFileModifiedDate As DateTime = IO.File.GetLastWriteTime(fileName)
              Dim dtCustomDate As DateTime = DateTime.ParseExact(20180401, "yyyyMMdd", Globalization.CultureInfo.InvariantCulture)
              If dtFileModifiedDate > dtCustomDate Then
                  filesListBox.Items.Add(fileName)
              End If
          Next
      End Sub
      

      【讨论】:

        猜你喜欢
        • 2018-05-11
        • 2023-03-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-11-01
        相关资源
        最近更新 更多