我有一些代码应该采用一个起始目录并循环遍历该目录和所有子目录,但是它会到达第一个分支中的最后一个子目录,然后退出并退出。我知道有很多这些,但我无法弄清楚如何通过最后一个子目录。我希望有人可以指出如何继续通过下一个目录分支。 (它只是检查超过1小时的文件并通过电子邮件发送给我,而且该部分工作正常,它无处可见。)
Sub Main()
Dim dirList As New String("C:\Users\Test\SampleDir")
Dim lOldNames = New List(Of String)()
ListFiles(dirList, lOldNames)
If lOldNames.Count > 0 Then
sendMail(lOldNames)
End If
End Sub
Public Function ListFiles(ByVal sdirList As String, ByVal lOldNames As List(Of String))
Dim dirList As New DirectoryInfo(sdirList)
Dim fiFileList As FileInfo() = dirList.GetFiles()
Dim fiName As FileInfo
Dim bEmpty As Boolean = False
bEmpty = IsDirectoryEmpty(dirList.ToString)
If bEmpty = False Then
For Each fiName In fiFileList
If fiName.CreationTime.AddHours(1) < DateTime.Now Then
lOldNames.Add(fiName.FullName)
End If
Next fiName
End If
Dim subDirs() As DirectoryInfo = dirList.GetDirectories()
For Each subdir As DirectoryInfo In subDirs
ListFiles(subdir.FullName, lOldNames)
Next subdir
Return lOldNames
End Function
'Function to test if directory is empty
Public Function IsDirectoryEmpty(ByVal path As String) As Boolean
Return Not (Directory.EnumerateFileSystemEntries(path).Any())
End Function
修正并缩短了以下史蒂夫评论中的函数调用:
Public Function ListFiles(ByVal sdirList As String, ByVal lOldNames As List(Of String))
Dim dirList As New DirectoryInfo(sdirList)
Dim fiFileList As FileInfo() = dirList.GetFiles()
Dim dirs As String() = Directory.GetFiles(sdirList, "*", SearchOption.AllDirectories)
For Each sfile As String In dirs
If Not sfile.Contains("Software") AndAlso Not sfile.Contains("Outbound") AndAlso Not sfile.Contains("RECYCLE.BIN") AndAlso Not sfile.Contains("System Volume") Then
Dim fiName As New FileInfo(sfile)
If fiName.CreationTime.AddHours(1) < DateTime.Now Then
lOldNames.Add(fiName.FullName)
End If
End If
Next
Return lOldNames
End Function