How would I write a recursive function to scan the Temp Files on a computer and list all the files & folders to a ListView?

Function GetListOfFiles(ByVal Path As String) As List(Of String)
        Dim Files() As String = System.IO.Directory.GetFiles(Path)
        Dim ListofFiles As New List(Of String)
        For I As Integer = 0 To UBound(Files)
            ListofFiles.Add(Files(I))
        Next
        Return ListofFiles
    End Function

U can call the above function by:

Dim temp as string = System.IO.Path.GetTempPath()
GetListOfFiles(temp)

actually:

Dim Filelist as new list(of string)
Dim Path as string = System.IO.Path.GetTempPath()
Filelist = GetListOfFiles(Path)

actually:

Dim Filelist as new list(of string)
Dim Path as string = System.IO.Path.GetTempPath()
Filelist = GetListOfFiles(Path)
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Dim Path As String = System.IO.Path.GetTempPath
        Dim ListOfDirectory As New List(Of String)
        Dim CompleteListofDirectory As New List(Of String)
        CompleteListofDirectory = GetDirectory(Path)

        Dim ListOfFiles As New List(Of String)

        For I As Integer = 0 To CompleteListofDirectory.Count - 1
            Dim Files As New List(Of String)
            Files = GetListOfFiles(CompleteListofDirectory(I))
            For J As Integer = 0 To Files.Count - 1
                ListOfFiles.Add(Files(J))
            Next
        Next

    End Sub
    Function GetListOfFiles(ByVal Path As String) As List(Of String)
        Dim Files() As String = System.IO.Directory.GetFiles(Path)
        Dim ListofFiles As New List(Of String)
        For I As Integer = 0 To UBound(Files)
            ListofFiles.Add(Files(I))
        Next
        Return ListofFiles
    End Function
    Function GetDirectory(ByVal Path As String) As List(Of String)
        Dim Directory() As String = System.IO.Directory.GetDirectories(Path)
        Dim Completelist As New List(Of String)
        For I As Integer = 0 To UBound(Directory)
            Completelist.Add(Directory(I))
        Next
        Dim Check As Boolean = True

        While Check = True
            Dim Count As Integer = 0
            For I As Integer = 0 To Completelist.Count - 1
                Directory = System.IO.Directory.GetDirectories(Completelist(I))
                For J As Integer = 0 To UBound(Directory)
                    Dim Isin As Boolean = False
                    For K As Integer = 0 To Completelist.Count - 1
                        If Completelist(K) = Directory(J) Then Isin = True
                    Next
                    If Isin = False Then
                        Completelist.Add(Directory(J))
                        Count += 1
                    End If
                Next
            Next
            If Count = 0 Then Check = False
        End While
        Return Completelist
    End Function

Edited 5 Years Ago by Ezzaral: Added code tags. Please use them to format any code that you post.

This will return an array of all file names in a specified directory including sub directories.

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
     
        Dim FileNames As String() = GetDirectoryFileNames(System.IO.Path.GetTempPath)

    End Sub

    ''' <summary>
    '''Gets the names of all files in the specified directory including sub directories.
    ''' </summary>
    ''' <param name="DirectoryPath"></param>
    ''' <remarks></remarks>
    Private Function GetDirectoryFileNames(ByVal directoryPath As String) As String()

        Dim FileNames() As String = New String() {}
        Dim TempNames() As String

        Try
            For Each FileName As String In System.IO.Directory.GetFiles(directoryPath)
                ReDim Preserve FileNames(FileNames.GetLength(0))
                FileNames(UBound(FileNames)) = FileName
            Next

            For Each Directory As String In System.IO.Directory.GetDirectories(directoryPath)
                TempNames = GetDirectoryFileNames(Directory)
                ReDim Preserve FileNames(FileNames.GetLength(0) + TempNames.GetLength(0) - 1)
                Array.Copy(TempNames, 0, FileNames, FileNames.GetLength(0) - TempNames.GetLength(0), TempNames.GetLength(0))
            Next

        Catch ex As Exception

        End Try

        Return FileNames

    End Function

OR

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
     
        Dim FileNames2 As String() = System.IO.Directory.GetFiles(System.IO.Path.GetTempPath, "*", IO.SearchOption.AllDirectories)

    End Sub

Edited 5 Years Ago by Unhnd_Exception: n/a

Thanks for all the help. Here is the code that completed it all.

Private Sub TSScan_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TSScan.Click
        'Declare Variables
        Dim temp As String = System.IO.Path.GetTempPath()
        Dim ListOfFiles() As String = System.IO.Directory.GetFiles(temp)
        Dim Counter As Integer = 0

        'Set Visibility Variable
        ScanInfo.Visible = False
        
        With ListView1.Columns 'Add Columns
            .Add("Path", 500) : .Add("Files", 100) : .Add("Size", 100)
        End With

        ListView1.View = View.Details ' Display Columns

        If IO.Directory.Exists(temp) Then
            For Each strFolder As String In IO.Directory.GetDirectories(temp)
                Dim DirectoryDetail As New DirectoryInfo(strFolder)
                Dim newDirectory As New ListViewItem(strFolder)
                Dim dirSize As Long = 0
                newDirectory.SubItems.Add("Folder")
                Try
                    Dim Fil As FileInfo
                    For Each Fil In DirectoryDetail.GetFiles()
                        dirSize += Fil.Length
                    Next Fil
                Catch ex As Exception

                End Try
                newDirectory.SubItems.Add(Math.Round((dirSize / 1024), 0, MidpointRounding.AwayFromZero) & " KB")
                ListView1.Items.Add(newDirectory)
            Next
        End If

        For I As Integer = 0 To UBound(ListOfFiles)
            Dim fileDetail As New FileInfo(ListOfFiles(I))
            Dim newItem As New ListViewItem(ListOfFiles(I))                                                                   'PATH
            newItem.SubItems.Add(IO.Path.GetExtension(ListOfFiles(I)))                                                        'File Type
            newItem.SubItems.Add(Math.Round((fileDetail.Length / 1024), 0, MidpointRounding.AwayFromZero) & " KB")      'File Size
            ListView1.Items.Add(newItem)                                                                                'ADD ALL DETAILS to LISTVIEW1
            Counter += 1
        Next

        FilesFoundCount.Text = Counter
    End Sub

The last part I need to figure out is how to run a recursive delete based on the list. 1) I need it delete all items in the list, 2) I need to delete the items only if they are checked in the ListView.

That doesn't actually work. It won't search sub folders.

I modified the code I posted to do what you want.

This will list each directory and all the items in the directory before listing the next directory.

You shouldn't need to recursively delete items. You should be able to iterate through the checked items and use the text of the item since its the path.

Use ListView.BeginUpdate and ListView.EndUpdate when adding or removing a bunch of items.

In this case using the update methods makes it run about 6 times faster.

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

        With ListView1.Columns 'Add Columns
            .Add("Path", 500) : .Add("Files", 100) : .Add("Size", 100)
        End With
        ListView1.View = View.Details ' Display Columns

        ListView1.BeginUpdate()
        ListView1.Items.Clear()
        Dim TotalFiles As Integer = FillListViewWithAllFilesAndFolders(System.IO.Path.GetTempPath)
        ListView1.EndUpdate
      
    End Sub


 Private Function FillListViewWithAllFilesAndFolders(ByVal directoryPath As String) As Integer

        Dim TotalFiles As Integer
        Dim Files() As String
        Dim DirectoryItem As ListViewItem
        Dim FileItem As ListViewItem
        Dim DirectoryFileSize As Integer
        Dim FileInfo As System.IO.FileInfo

        Try
            'Get all the files in the directory
            Files = System.IO.Directory.GetFiles(directoryPath)
            TotalFiles += Files.Count

            'Add the directory.
            DirectoryItem = New ListViewItem(directoryPath)
            DirectoryItem.SubItems.Add("Folder")

            ListView1.Items.Add(DirectoryItem)

            'Add each file and file size
            'Increment the file sizes and add to the directory
            'item when done.
            For i = 0 To UBound(Files)
                FileInfo = New System.IO.FileInfo(Files(i))

                FileItem = New ListViewItem(Files(i))
                FileItem.SubItems.Add("File")
                FileItem.SubItems.Add(Math.Round(FileInfo.Length / 1024, 2).ToString)

                ListView1.Items.Add(FileItem)

                DirectoryFileSize += FileInfo.Length
            Next

            'Add the the total file size in the directory
            'to the directory item
            DirectoryItem.SubItems.Add(Math.Round(DirectoryFileSize / 1024, 2).ToString)

            'Repeat the process for each item in all
            'directories.
            For Each Directory As String In System.IO.Directory.GetDirectories(directoryPath)
                TotalFiles = FillListViewWithAllFilesAndFolders(Directory)
            Next

        Catch ex As Exception

        End Try

        Return TotalFiles

    End Function

I don't need to know what's inside the child folders. Just wanted to the folders were inside the %TEMP% folder.

Heres one question:
How would I write a recursive function to scan the Temp Files on a computer and list all the files & folders to a ListView?

Heres another:
How would I include folders that are inside the TEMP location?

We'll just let this one go un-solved.

So I have everything working except for the ability to delete folders that might be in the %TEMP% folder. I get an error of " The value of argument 'onDirectoryNotEmpty' (-1) is invalid for Enum type 'DeleteDirectoryOption'.
Parameter name: onDirectoryNotEmpty".

I also had an ListView1.BeginUpdate() and ListView1.EndUpdate() but it wipes out the remainder of my list items.

Private Sub TSDeleteSelected_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TSDeleteSelected.Click
        'DELETE ONLY SELECTED ITEMS
        Dim I As Integer
        For I = ListView1.Items.Count - 1 To 0 Step -1
            If ListView1.Items(I).Checked = True Then
                If ListView1.Items(I).SubItems(1).Text = "Folder" Then
                    My.Computer.FileSystem.DeleteDirectory(ListView1.Items(I).SubItems(0).Text, True)
                    ListView1.Items.RemoveAt(I)
                Else
                    System.IO.File.Delete(ListView1.Items(I).SubItems(0).Text)
                    ListView1.Items.RemoveAt(I)
                End If
            End If
        Next I
    End Sub
My.Computer.FileSystem.DeleteDirectory(ListView1.Items(I).SubItems(0).Text, True)

True is not an option for onDirectoryNotEmpty. Change it to one of the enum values.

My.Computer.FileSystem.DeleteDirectory(ListView1.Items(I).SubItems(0).Text, FileIO.DeleteDirectoryOption.DeleteAllContents)

BeginUpdate and EndUpdate just tells the list view to not lay itself out until you tell it to. It should not wipe anything out.

This article has been dead for over six months. Start a new discussion instead.