You must have heard about recursive programming. If not, then take a look of it on Wikipedia. In recursive programming, the function or method calls itself. This may seem confusing but after looking at the code below, it will be easy enough for you.
Code below scans entire file system and lists scanned files into a listbox named ‘scannedFiles’
Code Snippet
- Public Class Form1
- Sub scanSubfolders(ByVal FolderLocation As String, ByVal List As ListBox)
- For Each s In My.Computer.FileSystem.GetFiles(FolderLocation)
- Try
- List.Items.Add(s)
- Catch ex As Exception
- End Try
- Next
- For Each s In My.Computer.FileSystem.GetDirectories(FolderLocation)
- Try
- scanSubfolders(s, List)
- Catch ex As Exception
- End Try
- Next
- End Sub
- Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
- BackgroundWorker1.RunWorkerAsync()
- End Sub
- Private Sub BackgroundWorker1_DoWork(ByVal sender As System.Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork
- CheckForIllegalCrossThreadCalls = False
- scanSubfolders("C:\", Me.scannedFiles)
- End Sub
- End Class
In the above code, the sub scanSunfolders() is calling itself again in line 13.
The scanSubfolders() is the main part. Within lines 5 and 7, you can do almost everything. Since ‘s’ is the file for instant, you can add an ‘if’ statement between lines 5 and 7 that filters only those files whose filenames end with ‘.mp3’ or any other extension. I have added ‘Try…Catch…End Try’ statement to evade file access errors if scanning a protected folder. This has been further illustrated below:
Code Snippet
- Sub scanSubfolders(ByVal FolderLocation As String, ByVal List As ListBox)
- For Each s In My.Computer.FileSystem.GetFiles(FolderLocation)
- Try
- If s.EndsWith(".mp3") Or s.EndsWith(".wav") Then
- List.Items.Add(s)
- End If
- Catch ex As Exception
- End Try
- Next
- For Each s In My.Computer.FileSystem.GetDirectories(FolderLocation)
- Try
- scanSubfolders(s, List)
- Catch ex As Exception
- End Try
- Next
- End Sub