VB.NET Scan Folder and File name for string

Ryan Lashway 61 Reputation points

I have found plenty of code to scan for a file name that contains a string, but how can I scan for a file name and folder/subfolder name that contains a string?

Ex. I want to search for all folders and files that have a label/name containing "secret"

I appreciate any help,

An object-oriented programming language developed by Microsoft that is implemented on the .NET Framework. Previously known as Visual Basic .NET.
2,496 questions
0 comments No comments
{count} votes

Accepted answer
  1. Viorel 109.8K Reputation points

    Check a relatively short approach:

    Dim folder = "C:\MyFolder"
    Dim string_to_find = "abc"
    Dim di = New DirectoryInfo(folder)
    Dim results = di.EnumerateFileSystemInfos("*", SearchOption.AllDirectories).Where(Function(i) i.Name.IndexOf(string_to_find, StringComparison.InvariantCultureIgnoreCase) >= 0)

    To display the found folders and files:

    For Each r In results
        If TypeOf r Is DirectoryInfo Then
            Console.WriteLine("Directory: {0}", r.Name)
            Console.WriteLine("File: {0}", r.Name)
        End If
    0 comments No comments

4 additional answers

Sort by: Most helpful
  1. Anonymous


    This sample will loop through a folder looking for a folder or file that contains the word. When it finds the word it will give the location of the file or folder. The example searches through the whole C:\ folder.

    Private Sub LoopThroughFolder(ByVal Folder As String, ByVal WordToSearchFor As String)
            Dim SubDirectories As String() = System.IO.Directory.GetDirectories(Folder)
            Dim Files As String() = System.IO.Directory.GetFiles(Folder)
            For i = 0 To SubDirectories.Length - 1
                If SubDirectories(i).Contains(WordToSearchFor) Then
                    MessageBox.Show("Found the string: " & WordToSearchFor & ", at the folder: " & SubDirectories(i))
                    Exit Sub
                End If
                LoopThroughFolder(SubDirectories(i), WordToSearchFor)
            For i = 0 To Files.Length - 1
                If Files(i).Contains(WordToSearchFor) Then
                    MessageBox.Show("Found the string: " & WordToSearchFor & ", at the file: " & Files(i))
                    Exit Sub
                End If
        End Sub

    If you want to search for a different word simply change this:

    Dim SearchWord As String = "secret"
    LoopThroughFolder("C:\", SearchWord)


    Dim SearchWord As String = "The word you want to search for"
    LoopThroughFolder("C:\", SearchWord)

    I hope it helps.

    1 person found this answer helpful.
    0 comments No comments

  2. Dewayne Basnett 1,041 Reputation points

    Like this

        Private Function WordInPath(startPath As String,
                                        findThis As String,
                                        Optional ignoreCase As Boolean = True,
                                        Optional searchSubFolders As Boolean = False) As List(Of String)
            Dim rv As New List(Of String)
            Dim path As String = If(ignoreCase, startPath.ToLower, startPath)
            Dim _find As String = If(ignoreCase, findThis.ToLower, findThis)
            If path.Contains(_find) Then rv.Add(path)
            Dim Files As String() = System.IO.Directory.GetFiles(path)
            For Each f As String In Files
                Dim _f As String = IO.Path.GetFileName(f)
                _f = If(ignoreCase, _f.ToLower, _f)
                If _f.Contains(_find) Then rv.Add(f)
            If searchSubFolders Then
                Dim SubDirectories As String() = System.IO.Directory.GetDirectories(path)
                For Each d As String In SubDirectories
                    rv.AddRange(WordInPath(d, findThis, ignoreCase, searchSubFolders))
            End If
            Return rv
        End Function
    1 person found this answer helpful.

  3. Ryan Lashway 61 Reputation points

    Works-ish, does this method not allow for "*" searches, as if I search say for "tem" via explorer I get 23 records, but via the code I get only the records with "tem" being the first part of the word, and I have to match case?

  4. Karen Payne MVP 35,011 Reputation points


    First off what I have to offer is for .NET Core 5, VB.NET so if not using these do not continue.

    What coders generally do not think about when searching for a value in a file is

    • What if the directory structure has a lot of folders, file and mixture of text base and binary files. This can cause an application to become unresponsive, code keeps the app responsive.
    • Folders/files the user of the application does not have permissions too, this when not considered will throw a run time exception
    • A method to cancel a search operation, for instance, a string value is entered that is incorrect, rather than wait it's wise to allow cancellation.

    The following article with robust code samples takes into consideration the above. Since there are several different paths to take by design, the code needs tweaks to accommodate specific needs.

    For instance, in the following screenshot there is a ListView to show what folders have been scanned, some may not want to display in a ListView, perhaps in a label.




    • Use of delegates and events are used which means you should understand them.
    • Asynchronous coding is used throughout, which means you should understand or willing to learn asynchronous coding (see this article)
    • Willing to spend time to adapt code your needs
    • To get the code, Git current version is needed and to use the script below mkdir code
      cd code
      git init
      git remote add -f origin https://github.com/karenpayneoregon/vb-vs2019-samples
      git sparse-checkout init --cone
      git sparse-checkout add FileHelpers
      git sparse-checkout add FolderBrowserDialog
      git sparse-checkout add RecurseFolders
      git pull origin master
      del .gitattributes
      del .gitignore
      del .yml
      del .editorconfig
      del *.md
      del *.sln
    0 comments No comments