Jedi
Jedi

Reputation: 153

Searching entire computer for specified file

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?

Upvotes: 0

Views: 592

Answers (3)

dummy
dummy

Reputation: 4284

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.

Upvotes: 1

alstonp
alstonp

Reputation: 700

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.

Upvotes: 4

AgentFire
AgentFire

Reputation: 9800

Try this:

Dim files() As String = System.IO.Directory.GetFiles("C:\", "file.dat")

Upvotes: 0

Related Questions