Pages

Wednesday, August 18, 2010

How to make your VB .NET application scan sub-folders for files?

Programming_Green
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
  1. Public Class Form1
  2.  
  3.     Sub scanSubfolders(ByVal FolderLocation As String, ByVal List As ListBox)
  4.         For Each s In My.Computer.FileSystem.GetFiles(FolderLocation)
  5.             Try
  6.                 List.Items.Add(s)
  7.             Catch ex As Exception
  8.  
  9.             End Try
  10.         Next
  11.         For Each s In My.Computer.FileSystem.GetDirectories(FolderLocation)
  12.             Try
  13.                 scanSubfolders(s, List)
  14.             Catch ex As Exception
  15.  
  16.             End Try
  17.         Next
  18.     End Sub
  19.  
  20.     Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
  21.         BackgroundWorker1.RunWorkerAsync()
  22.     End Sub
  23.  
  24.     Private Sub BackgroundWorker1_DoWork(ByVal sender As System.Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork
  25.         CheckForIllegalCrossThreadCalls = False
  26.         scanSubfolders("C:\", Me.scannedFiles)
  27.     End Sub
  28. 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
  1. Sub scanSubfolders(ByVal FolderLocation As String, ByVal List As ListBox)
  2.     For Each s In My.Computer.FileSystem.GetFiles(FolderLocation)
  3.         Try
  4.             If s.EndsWith(".mp3") Or s.EndsWith(".wav") Then
  5.                 List.Items.Add(s)
  6.             End If
  7.         Catch ex As Exception
  8.  
  9.         End Try
  10.     Next
  11.     For Each s In My.Computer.FileSystem.GetDirectories(FolderLocation)
  12.         Try
  13.             scanSubfolders(s, List)
  14.         Catch ex As Exception
  15.  
  16.         End Try
  17.     Next
  18. End Sub
Experiment with this code yourself. If you have any suggestions, problems or queries, please feel free to comment.

Ads

Look into BLOG ARCHIVE for more posts.