不确定如何为我的问题标题写词。但希望这会很快。
我的文件夹中有一堆PDF文件,我想获取某种文件类型的最近修改或创建日期。我的代码可以工作,但是它可以为我提供所有PDF文件的结果。我只想要某些名称的结果。
例如。在我的“ c:\ temp \”中,我有一些PDF文件,它们的开头几乎是相同的3个字母,然后是数字或更多字母。
文件名,例如tes8796,fes8897895,bas232。等等等等。我只想显示“ fes”和“ bas”文件的结果,我不想看到“ tes”文件...
有任何想法吗?
我相信它应该看起来像这样{“ fes * .pdf”,“ Bas * .pdf”})
我的代码有效,(我只想获取“ fes”和“ bas” fils的结果。)
Dim pathx As String = "C:\temp\"
Dim directory = New DirectoryInfo(pathx)
Dim from_date As DateTime = DateTime.Now.AddHours(-24)
Dim to_date As DateTime = DateTime.Now
Dim files = directory.GetFiles().Where(Function(file) file.LastWriteTime >= from_date AndAlso file.LastWriteTime <= to_date)
For Each filx In files
ListBox1.Items.Add(filx)
Next
有多种方法可以做到这一点。首先,您可以在开始处应用PDF过滤器:directory.GetFiles("*.pdf")
,然后扩展您的功能条件:
Dim names() As String = {"fes", "bas"}
Dim files = di.GetFiles("*.pdf").Where(
Function(file) (file.LastWriteTime >= from_date _
AndAlso file.LastWriteTime <= DateTime.Now) _
AndAlso (names.Contains(file.Name.ToLowerInvariant.Substring(0, 3)))
)
For Each filx In files
Console.WriteLine(filx)
Next
问题在于,它取决于文件的起始名称始终为3个字符。另外,请看一下代码:获得数组后,就循环遍历该数组以将其发布到ListBox。通常,很酷的孩子使用LINQ来避免循环。因此,要解决这两个问题:
ListBox1.Items.AddRange(di.GetFiles("*.pdf").Where(
Function(f) (f.LastWriteTime >= from_date AndAlso f.LastWriteTime <= DateTime.Now) _
AndAlso names.Any(Function(n) f.Name.ToLowerInvariant.StartsWith(n))
).ToArray)
我摆脱了NET中已经存在的var名称,例如Directory
和File
。第二个函数对names数组进行过滤,然后将结果直接输入到列表框项目集合中。
在几乎所有情况下,纯循环都会更快:
Dim myfiles = directory.GetFiles("*.pdf")
For Each f In myfiles
If f.LastAccessTime >= from_date AndAlso f.LastWriteTime <= DateTime.Now Then
For Each s As String In names
If f.Name.ToLowerInvariant.StartsWith(s.ToLowerInvariant) Then
Console.WriteLine(f)
Exit For ' abort when found
End If
Next
End If
Next
Console.WriteLine
可以根据需要添加到“项”或“添加到列表”。)a时间差是否重要取决于其使用方式和负载。如果它连续运行以处理许多文件,则可能很重要。作为桌面应用程序的一部分,可能不是。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句