我正在编写一个程序,它会迭代"每个"在计算机上的文件。它从搜索中排除某些目录,例如回收站和临时和Windows系统文件。有一个子程序可以在每个驱动器的根目录中搜索文件,然后递归搜索每个子目录中的文件。有SortedSet(Of String)
个排除目录(用于快速查找),当搜索与排除目录匹配时,它会跳过它并将其从排除列表中删除以减少比较次数。
有一个子程序用于向排除集添加新目录。子例程的功能是仅添加不是集合中已包含的其他目录的子目录的目录,并删除集合中已包含的任何目录(如果它们是要添加的目录的子目录)。 / p>
以下是我解决问题的方法。排除目录的确切位置无法事先知道,是否有更简洁和/或更有效的算法可用于此目的?
Sub ExcludeDirectory(directoryPath As String)
'For simple case-insensitive comparison all paths are converted to lower-case prior to comparison.
directoryPath = directoryPath.ToLower
'Append the final '\' to the candidate if it is missing. This avoids issues with directories not being added to the exclusion list due to sharing an already listed directories path as a prefix but not actually being a subdirectory of that listed directory.
'For Example: C:\Program Files Compare To: C:\Program Files\
' C:\Program Files (x86) C:\Program Files (x86)\
If Not directoryPath.EndsWith("\") Then directoryPath &= "\"
'Do loop chosen since items in the exclusion list will be removed if they are subdirectories of the candidate directory.
Dim i As Integer = 0
Do Until i = ExcludedDirectories.Count
'Multiple listed directories may be subdirectories of candidate but the reverse is not the case so evaluating the first case is done first.
If ExcludedDirectories(i).StartsWith(directoryPath) Then
'If any listed directory is a subdirectory of the candidate then remove it. Do not increment 'i' because the next directory will be located at the same index.
ExcludedDirectories.Remove(ExcludedDirectories(i))
ElseIf directoryPath.StartsWith(ExcludedDirectories(i)) Then
'If the candidate is a subdirectory of any listed directory then it will not be added and does not need comparison to any other directories.
Exit Sub
Else
i += 1
End If
Loop
'Add candidate directory.
ExcludedDirectories.Add(directoryPath)
End Sub