0
votes

I've got a little project on the go which requires a recursive scan over folder and sub-folders (starting from a top directory of the users' choice (TextBox_folder_select), searching for files with a chosen extension (TextBox_Extension.Text), then adding the file name to a listbox. I've started with this:

    Dim Folder As New IO.DirectoryInfo(TextBox_folder_select.Text)
    For Each File As IO.FileInfo In Folder.GetFiles("*." & TextBox_Extension.Text, IO.SearchOption.AllDirectories)
        ListBox1.Items.Add(File.Name)
    Next

...which works well where the user has full access to the directory tree, however using 'IO.SearchOption.AllDirectories' method throws up errors (System.UnauthorizedAccessException) when a user selects a path containing directories they don't have rights to access.

EDIT x 2:

OK, Rumpelstinsk had guided me towards a partial answer:

    Delegate Sub processfiledelegate(ByVal path As String)
Sub main()
    Dim path = TextBox_folder_select.Text
    Dim ext = "*." & TextBox_Extension.Text

    Dim runprocess As processfiledelegate = AddressOf processfile
    applyallfiles(path, ext, runprocess)
End Sub

Sub processfile(ByVal path As String)
    Dim files As String
    files = IO.Path.GetFileName(path)
    ListBox1.Items.Add(files)
End Sub

Sub applyallfiles(ByVal folder As String, ByVal extension As String, ByVal fileaction As processfiledelegate)
    For Each File In Directory.GetFiles(folder, extension)
        fileaction.Invoke(File)
    Next
    For Each subdir In Directory.GetDirectories(folder)
        Try
            applyallfiles(subdir, extension, fileaction)
        Catch ex As Exception
        End Try
    Next
End Sub

Whilst i don't yet fully understand the use of a 'delegate', it's something i can read up on. The listbox now contains all the paths of all the files with the extension as selected. Nice start. Thanks.

Exponent then suggested how to to show the file name, rather than the full path. Thanks.

In order to then allow a user to open that selected file from the list box, i re-ran the delegate sub routines specifically looking for that file name. Seems to work well.

Thanks all, again.

1
Your option is to implement AllDirectories yourself through recursion or a stack.the_lotus

1 Answers

0
votes

You could add the result of this function to your listbox:

IO.Path.GetFileName(path)

or

IO.Path.GetFileNameWithoutExtension(path)