Tuesday, February 24, 2009

Browsing trough files programaticaly

To browse trough the filesystem .net provides in System.IO namespace two very useful functions:  Directory.GetFiles  and Directory.GetDirectories. What those functions do is quite obvious. Simple example below.

Public Function SearchForFile(ByVal targetDirectory As String, ByVal fileToFind As String, ByVal recursive As Boolean) As String
    Dim fileName As String = String.Empty

    If fileToFind IsNot Nothing Then
      Dim fileEntries As String() = Directory.GetFiles(targetDirectory)
      ' Process the list of files found in the directory.

      For Each fileName In fileEntries
        If fileName.ToLower.Contains(fileToFind) Then
          Return fileName
        End If
      Next fileName

      If recursive Then
        Dim subdirectoryEntries As String() = Directory.GetDirectories(targetDirectory)
        ' Recurse into subdirectories of this directory.
        Dim subdirectory As String
        For Each subdirectory In subdirectoryEntries
          SearchForFile(subdirectory, fileToFind, recursive)
        Next subdirectory
      End If
    End If

    Return fileName

  End Function

No comments: