# Recursively Listing Files In A Directory And Adding Their Names To A Text File In Visual Basic .NET

I am making a program that I will use to read files in a particular folder and put those file names into a text file. How can I do this?

This is actually pretty easy to do in VB.NET, and there are several other examples on the Web. But it’s been a while since I’ve written anything on VB.NET, so I figured I would do this one.

I will accomplish this task with two subroutines. The first is a recursive subroutine that accepts a file path (e.g., C:\path\to\some\directory), scans all its subdirectories for files, and returns the name of each file to a second subroutine.

That second subroutine adds the passed file name to a text file.

### Step 1: The GetAllFiles() Subroutine

As previously noted, our first subroutine accepts the opening file path as its argument.

• The subroutine ensures the directory exists.
• If the directory exists, the subroutine gets a list of all current subdirectories, and sends each of those subdirectories to this same function via a For Each loop. If you do not want to scan subdirectories for file names, then simply comment out the first For Each loop.
• The subroutine finally gets all the files in the directory and sends their names to the AddFileName subroutine.
Imports System.IO

Sub GetAllFiles(strPath As String)
Dim objRoot As New DirectoryInfo(strPath)
Dim objSubDir As DirectoryInfo()
Dim objFile As FileInfo()

If objRoot.Exists Then
'if you don't want this to be recursive, remove this for loop
For Each objSubDir In objRoot.GetDirectories
GetAllFiles(objSubDir.FullName)
Next

'keep this for loop
For Each objFile In objRoot.GetFiles
Next
End If
End Sub


### Step 2: The AddFileName() Subroutine

The AddFileName subroutine will actually add our file name, its only argument, to the text file.

• It checks to see if the output file exists; if not, the file is created.
• A StreamWriter is created and the output file is opened for appending.
• The file name is added as a line to the text file, which is then closed.
Sub AddFileName(strName As String)
Dim strOutput As String = "C:\\path_to_output.txt"
If Not File.Exists(strOutput) Then
File.CreateText(strOutput)
End If

Dim objStream As StreamWriter = File.AppendText(strOutput)
objStream.WriteLine(strName)
objStream.Flush()
objStream.Close()
End Sub


That’s all there is to it.

This code as a Gitub Gist: https://gist.github.com/dougvdotcom/f66999fa71af2a12b1e2

1. Nick says:

There is a mistake in the code. DirectoryInfo does not have a property named “FullPath”:-

GetAllFiles(objSubDir.FullPath)

GetAllFiles(objSubDir.FullName)