Atlanta Custom Software Development 

 
   Search        Code/Page
 

User Login
Email

Password

 

Forgot the Password?
Services
» Web Development
» Maintenance
» Data Integration/BI
» Information Management
Programming
  Database
Automation
OS/Networking
Graphics
Links
Tools
» Regular Expr Tester
» Free Tools

How to perform recursive search for files or folders in VB.net

Total Hit ( 4740)

Rate this article:     Poor     Excellent 

 Submit Your Question/Comment about this article

Rating


 


This is a very common requirement to find all or specific files in a specified foder and all subfolders.

You can use GetDirectories and GetFiles of System.IO.DirectoryInfo for this purpose. Check the following example.

Click here to copy the following block
Sub FindFilesDemo()
  Dim msg As String
  Dim ar As New ArrayList
  Dim fi As System.IO.FileInfo
  'ar = GetFiles(Server.MapPath("."), "*.aspx")
  ar = DoRecursiveSearch("C:\Inetpub\wwwroot\BWCart", "*.aspx")
  'Response.Write("<Pre>")
  For Each fi In ar
    msg = msg & "File Path: " & fi.FullName & vbCrLf
    msg = msg & "File Size: " & fi.Length & vbCrLf
    msg = msg & "Last Modified: " & fi.LastWriteTime & vbCrLf
    msg = msg & "---------------------------" & vbCrLf
    Console.WriteLine(msg)
  Next
  'Response.Write("</Pre>")
End Sub


Public Function DoRecursiveSearch(ByVal DirPath As String, _
  Optional ByVal FileSearchPattern As String = "*.*", _
  Optional ByVal FolderSearchPattern As String = "*", _
  Optional ByVal Recursive As Boolean = True) As ArrayList
  ' Specify the directories you want to manipulate.
  Dim di As System.IO.DirectoryInfo = New System.IO.DirectoryInfo(DirPath)
  Dim ar As New ArrayList
  Try
    ' Get only subdirectories
    Dim dirs As System.IO.FileSystemInfo() = di.GetDirectories(FolderSearchPattern)
    Dim files As System.IO.FileSystemInfo()
    Dim diNext As System.IO.DirectoryInfo
    Dim fiNext As System.IO.FileInfo

    files = di.GetFiles(FileSearchPattern)
    For Each fiNext In files
      ar.Add(fiNext)
    Next

    If Recursive Then
      For Each diNext In dirs
        ar.AddRange(DoRecursiveSearch(diNext.FullName, FileSearchPattern, FolderSearchPattern, Recursive))
      Next
    End If

    Return ar
  Catch e As Exception
    Console.WriteLine("The process failed: {0}", e.ToString())
  End Try

End Function


Submitted By : Nayan Patel  (Member Since : 5/26/2004 12:23:06 PM)

Job Description : He is the moderator of this site and currently working as an independent consultant. He works with VB.net/ASP.net, SQL Server and other MS technologies. He is MCSD.net, MCDBA and MCSE. In his free time he likes to watch funny movies and doing oil painting.
View all (893) submissions by this author  (Birth Date : 7/14/1981 )


Home   |  Comment   |  Contact Us   |  Privacy Policy   |  Terms & Conditions   |  BlogsZappySys

© 2008 BinaryWorld LLC. All rights reserved.