.Net print directory list file names only to file

Using vb.Net
I would like to output to a text file a list of the file names in a directory.
Larry Bristersr. DeveloperAsked:
Who is Participating?
Fernando SotoConnect With a Mentor RetiredCommented:
Hi lrbrister;

Here is sample code to do what you want.
Private Sub SaveFilenamesToFile(ByVal sourceDir As String, ByVal destDir As String, ByVal saveFileAs As String)
    '' Make sure that the Source Directory does exist
    If Not Directory.Exists(sourceDir) Then
        MessageBox.Show("Source Directory " + sourceDir + " Doest Not Exist")
    End If

    '' Make sure that the Destination Directory does exist
    If Not Directory.Exists(destDir) Then
        MessageBox.Show("Destination Directory " + destDir + " Doest Not Exist")
    End If

    '' Get the DirectoryInfo for the source directory
    Dim sDir = FileIO.FileSystem.GetDirectoryInfo(sourceDir)
    '' Get an array of FileInfo in the directory
    Dim names = sDir.GetFiles("*")

    '' Create / open the destination file
    Dim fs = File.Open(destDir & "\" & saveFileAs, FileMode.OpenOrCreate, FileAccess.Write)
    '' Get a stream writer
    Dim sw As New StreamWriter(fs)
    '' Writes the directiory name as the first line in the file
    sw.WriteLine("Directory " + destDir)
    sw.WriteLine(" ")
    '' Write all the file names to the file stream
    For Each name As FileInfo In names
    '' Clean up
End Sub

Open in new window

You can call the above function as follows
SaveFilenamesToFile("C:\Working Directory", "C:\Working Directory\Test", "Filename.txt")

Open in new window

Chris StanyonConnect With a Mentor Commented:
Simple example:

Dim dir As New IO.DirectoryInfo(Directory.GetCurrentDirectory())

Using sw As StreamWriter = New StreamWriter(Path.Combine(dir.FullName, "files.txt"))

    Dim files As IO.FileInfo() = dir.GetFiles()

    For Each file In files
    Next file

End Using

Open in new window

Larry Bristersr. DeveloperAuthor Commented:
Thanks guys... sorry for the late get back
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.