0 Replies - 2266 Views - Last Post: 13 February 2016 - 09:15 AM

#1 andrewsw   User is offline

  • Bouncy!
  • member icon

Reputation: 6562
  • View blog
  • Posts: 26,614
  • Joined: 12-December 12

List all files, including subfolders

Posted 13 February 2016 - 09:15 AM

Here is my attempt to iterate all files, including all files within subfolders, ignoring UnathorizedAccessException (and other Exceptions) along the way.

It's a WinForm application with a TextBox, Button and ListBox.
Imports System.IO

Public Class Form1

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        ListFilesAndFolders(TextBox1.Text)
    End Sub

    Private Sub ListFilesAndFolders(location As String)

        For Each sPath In Directory.GetDirectories(location)
            ListBox1.Items.Add(sPath)
            Try
                ListFilesAndFolders(sPath)
            Catch ex As Exception
                Debug.Print(ex.Message)
                'ignore, only iterating
            End Try
        Next
        Try
            For Each sFile In Directory.GetFiles(location)
                ListBox1.Items.Add(sFile)
            Next
        Catch ex As UnauthorizedAccessException
            Debug.Print("Unauthorized file access")
        Catch ex As Exception
            'ignore
        End Try

    End Sub
End Class

Test it on small folders first, a large folder will take a long time.

The answer here at SO indicates some of the exceptions that could occur. It also takes a slightly different approach, wrapping the whole block in Try..Catch. I prefer to wrap the folder and file iterations in separate Try..Catch blocks. To me it's more explicit this way, saying "skip past this folder" and "skip past this file".

This isn't as straightforward as one would think, and you'll find other variations if you search.

This slight variation will list all the files before the subfolders, which might be considered a more natural order:
Imports System.IO

Public Class Form1

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        ListFilesAndFolders(TextBox1.Text)
    End Sub

    Private Sub ListFilesAndFolders(location As String)
        ListBox1.Items.Add(location)
        Try
            For Each sFile In Directory.GetFiles(location)
                ListBox1.Items.Add(sFile)
            Next
        Catch ex As UnauthorizedAccessException
            Debug.Print("Unauthorized file access")
        Catch ex As Exception
            'ignore
        End Try
        For Each sPath In Directory.GetDirectories(location)
            Try
                ListFilesAndFolders(sPath)
            Catch ex As Exception
                Debug.Print(ex.Message)
                'ignore, only iterating
            End Try
        Next


    End Sub
End Class



Is This A Good Question/Topic? 0
  • +

Page 1 of 1