问题
Is there a way to search the entire computer and get the full file path of specified file, given a filename to match against?
If you enter for example "file.dat" in textbox it show you full file path if it exist?
回答1:
Look into the Directory
class in System.IO
.
Whichever solution you use, avoid using GetFiles()
instead use EnumerateFiles()
since EnumerateFiles()
is recommended for large arrays. (In your case the entire C drive)
As per the MSDN documentation:
Enumerable collections provide better performance than arrays when you work with large collections of directories and files.
回答2:
Try this:
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
Be aware this is quite slow. You might want to give your user some indication which directory you currently searching (modify the FindInDirectory-Function for this).
Edit: Changed Get-Functions to Enumerate-Functions, as for alstonp suggestion.
回答3:
Try this:
Dim files() As String = System.IO.Directory.GetFiles("C:\", "file.dat")
来源:https://stackoverflow.com/questions/18889714/searching-entire-computer-for-specified-file