有没有办法搜索整个计算机并获取指定文件的完整文件路径,给定一个匹配的文件名?
如果您在文本框中输入“file.dat”,它会显示完整的文件路径(如果存在)?
答案 0 :(得分:4)
查看Directory
中的System.IO
课程。
无论您使用哪种解决方案,请避免使用GetFiles()
代替使用EnumerateFiles()
,因为EnumerateFiles()
is recommended for large arrays.(在您的情况下是整个C驱动器)
根据MSDN文档:
当您处理大量目录和文件时,可枚举集合提供的性能优于数组。
答案 1 :(得分:1)
试试这个:
Sub Main()
Dim filesFound = FindAllFiles("*.exe")
For Each item In filesFound
Console.WriteLine(item)
Next
End Sub
Private Function FindAllFiles(filename As String) As List(Of String)
Dim retVal As New List(Of String)
For Each item In IO.DriveInfo.GetDrives()
FindInDirectory(New IO.DirectoryInfo(item.Name), filename, retVal)
Next
Return retVal
End Function
Private Sub FindInDirectory(directory As IO.DirectoryInfo, filename As String, filesFound As List(Of String))
Try
For Each item In directory.EnumerateFiles(filename)
filesFound.Add(item.FullName)
Next
For Each item In directory.EnumerateDirectories()
FindInDirectory(item, filename, filesFound)
Next
Catch ex As System.IO.IOException
'Device not ready, most likely a DVD Drive with no media
Catch ex As System.UnauthorizedAccessException
' Directory is not accessable
End Try
End Sub
请注意这很慢。您可能希望为您的用户指出您当前正在搜索的目录(为此修改FindInDirectory-Function)。
编辑:将获取函数更改为枚举函数,与alstonp建议一样。
答案 2 :(得分:0)
试试这个:
Dim files() As String = System.IO.Directory.GetFiles("C:\", "file.dat")