Search - Articles
DevASP.NET for ASP.NET, VB.NET, XML and C# (C-Sharp) Developers Tuesday, March 03, 2009
Dev Articles
Search Directory
SQL Server

Loop through all sub categories and display all files under these using Visual Basic.Net

Author: Shahzad

Some times we need to process all the files in all the sub directories under one root directory, This article shows you the process using VB.Net code.

First of all place a ListBox control and a Button control on a windows form in Visual Basic.Net windows project, and name them lbFiles and cmdBrowse respectively. Also, add a FolderBrowseDialog control to open the root folder or directory through which you want to loop to get all the files under all sub directories. Name the FolderBrowseDialog control as FBD.


We’ll be using a recursive approach to process all directories. By the way, recursive approach is the one in which a function or a sub procedure calls itself until a particular condition is satisfied. So, write a routine that takes a directory name as input and process all of its files and subdirectories and so on.


Here is the code for this sub routine.


 Private Sub DisplayFiles(ByVal DirPath As String)

    Dim FileList As String() = Directory.GetFiles(DirPath)

    Dim DirList As String() = Directory.GetDirectories(DirPath)


    Dim FileName As String


    For Each FileName In FileList




    Dim DirectoryName As String


    For Each DirectoryName In DirList




  End Sub

Now, add following code in the click event of the button.

    Dim Root As String


    If FBD.ShowDialog() = DialogResult.OK Then

      Root = FBD.SelectedPath


      Exit Sub

    End If




You also need to add the following line on the top of the code.


 Imports System.IO

The above code will show up a Folder Browse Dialog and the selected folder’s path will be saved in a string variable named Root.  If no directory was selected then program will exit the sub routine.  

However, if some directory was selected then the method call given after the if condition will initiate the process and all the sub directories and all the files under these subdirectories will be processed and added in the ListBox we have already placed.

Article Comments
I liked your article but I could not get the code to work in VB.NET 2003. The error was " Name 'Directory' is not declared." Is there an "Inherits" clause that I am missing?


Posted on 12/11/2006 3:58:04 PM by Sherwood

Sherwood, you need to import the System.IO namespace.

Posted on 3/13/2008 4:55:32 AM by AL

Dear Sherwood and AL,

Thank you for identifying and giving the solution to the problem in the article.

Correction has been made.


DevASP Team

Posted on 4/23/2008 12:14:55 PM by DevASP Team

Add Article Comment:
Name :
Email Address :
Comments :
<< How to access a web page in Windows Form using Visual Basic.Net.

Disclaimer - Privacy
© 2002-2018