Search code examples
.netvb.netfilefolderbrowserdialog

VB.NET - Select all .txt files, including sub directory


I need to make a tool that will pick every .txt file in its folder and subfolders. I came to a point that the tool will pick every .txt file in its folder, but I don't know how to instantly also pick from all the subfolders.

Here is a code sample to let you know what I did, hope you could help me.

Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
        Dim fbd As FolderBrowserDialog = New FolderBrowserDialog() With {
            .Description = "Select a path",
            .SelectedPath = "C:\Users\klaasjelle\Documents\Visual Studio 2017\Projects\WindowsApp2\WindowsApp2\bin\Debug"
        }

        If fbd.ShowDialog() = DialogResult.OK Then
            TextBox1.Text = fbd.SelectedPath
        End If

        Dim dinfo As New DirectoryInfo(TextBox1.Text)

        Dim files As FileInfo() = dinfo.GetFiles("*.txt")

        ListBox1.Items.Clear()
        For Each file As FileInfo In files
            ListBox1.Items.Add(file.Name)
        Next

    End Sub

Solution

  • You should use dinfo.GetFiles("*.txt", SearchOption.AllDirectories) as said in the link:

    https://msdn.microsoft.com/pl-pl/library/ms143448(v=vs.110).aspx?cs-save-lang=1&cs-lang=vb#code-snippet-2