[SOLVED] How to get full path to file?

littlebigman

Well-known member
Joined
Jan 5, 2010
Messages
75
Programming Experience
Beginner
Hello

This is the simplest example Google returned to show how to recurse through a directory and find all files beneath it.

The only thing I'm missing is how to prepend the full path to each file, so that I can locate it later:

VB.NET:
Imports System.IO

Public Class Form1
    Private Sub RecursiveSearch(ByRef strDirectory As String, ByRef array As ArrayList)
        Dim dirInfo As New IO.DirectoryInfo(strDirectory)

        Dim pFileInfo() As IO.FileInfo
        Try
            pFileInfo = dirInfo.GetFiles()
        Catch ex As UnauthorizedAccessException
            MessageBox.Show(ex.Message, "Exception!", MessageBoxButtons.OK, MessageBoxIcon.Error)
            Exit Sub
        End Try

        array.AddRange(pFileInfo)

        Dim pdirInfo() As IO.DirectoryInfo
        Try
            pdirInfo = dirInfo.GetDirectories()
        Catch ex As UnauthorizedAccessException
            MessageBox.Show(ex.Message, "Exception!", MessageBoxButtons.OK, MessageBoxIcon.Error)
            Exit Sub
        End Try

        Dim dirIter As IO.DirectoryInfo
        For Each dirIter In pdirInfo
            RecursiveSearch(dirIter.FullName, array)
        Next dirIter
    End Sub

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Dim strDirectory As String = "C:\MyFiles\"
        Dim array As New ArrayList
        Dim i As Integer

        RecursiveSearch(strDirectory, array)

        'How to get full path to files?
        For i = 0 To array.Count - 1
            'ListBox1.Items.Add(array.Item(i).
            ListBox1.Items.Add(array.Item(i))
        Next
    End Sub
End Class

How can I get the full path to a file before adding it to the ListBox?

Thank you for any help.
 
Last edited:
VB.NET:
CType(array(i), IO.FileInfo).FullPath
Also, change both your ByRef parameters to ByVal.
Instead of ArrayList you should use List(Of T), in this case List(Of IO.FileInfo). When accessing an item you will then not need to cast from Object type to the target type. This also provides type safety in that only items of that type can be added to the List.
If only the FullPath is of interest you should use IO.Directory and IO.File objects instead.
 
Thanks much for the help. I failed switching to IO.Directory and IO.File, but anyway, .Net already provides a method to recurse through a directory:

VB.NET:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    Dim filelist As Collections.ObjectModel.ReadOnlyCollection(Of String) = My.Computer.FileSystem.GetFiles("C:\MyFiles\", FileIO.SearchOption.SearchAllSubDirectories)
    For Each path As String In filelist
        ListBox1.Items.Add(path)
    Next
End Sub

Thanks again.
 
Back
Top