Search Directories and Sub Directories

Posted on 2006-05-05
Last Modified: 2010-04-23
Does anybody know a good way to search a directory and its sub directories for a particular file type and copy them over to another place?  I cannot hardcode the search path so I need something that will search a directory tree.

Thanks in advance.
Question by:ndegioia
    LVL 39

    Accepted Solution

    if you are using VS 2005 you can use Directory.GetFiles Method

    for each sfilename  as string in"startpath","file pattern", AllDirectories)
    LVL 4

    Author Comment

    Nevermind I figured something out based on a sub routine I found on the web:

     Private Sub RecursiveCopyFiles( _
        ByVal sourceDir As String, _
        ByVal destDir As String, _
        ByVal fRecursive As Boolean, ByVal overWrite As Boolean)

            Dim i As Integer
            Dim posSep As Integer
            Dim sDir As String
            Dim aDirs() As String
            Dim sFile As String
            Dim aFiles() As String

            ' Add trailing separators to the supplied paths if they don't exist.
            If Not sourceDir.EndsWith(System.IO.Path.DirectorySeparatorChar.ToString()) Then
                sourceDir &= System.IO.Path.DirectorySeparatorChar
            End If

            If Not destDir.EndsWith(System.IO.Path.DirectorySeparatorChar.ToString()) Then
                destDir &= System.IO.Path.DirectorySeparatorChar
            End If

            ' Recursive switch to continue drilling down into dir structure.
            If fRecursive Then

                ' Get a list of directories from the current parent.
                aDirs = System.IO.Directory.GetDirectories(sourceDir)

                For i = 0 To aDirs.GetUpperBound(0)

                    ' Get the position of the last separator in the current path.
                    posSep = aDirs(i).LastIndexOf("\")

                    ' Get the path of the source directory <-- Run this if you want to duplicate the source file structure
                    'sDir = aDirs(i).Substring((posSep + 1), aDirs(i).Length - (posSep + 1))

                    ' Create the new directory in the destination directory.
                    System.IO.Directory.CreateDirectory(destDir + sDir)

                    ' Since we are in recursive mode, copy the children also
                    RecursiveCopyFiles(aDirs(i), (destDir + sDir), fRecursive, overWrite)

            End If

            ' Get the CSV files from the current parent.
            aFiles = System.IO.Directory.GetFiles(sourceDir, "*.csv")

            ' Copy all files.
            For i = 0 To aFiles.GetUpperBound(0)

                ' Get the position of the trailing separator.
                posSep = aFiles(i).LastIndexOf("\")

                ' Get the full path of the source file.
                sFile = aFiles(i).Substring((posSep + 1), aFiles(i).Length - (posSep + 1))

                    ' Copy the file.
                    System.IO.File.Copy(aFiles(i), destDir + sFile, False)
                    'addToConsoleWindow("Copied " & sFile & " to " & destDir)
                Catch ex As Exception
                    If overWrite = False Then
                        'addToConsoleWindow("Skipping..." & ex.Message)
                        System.IO.File.Copy(aFiles(i), destDir + sFile, True)
                        'addToConsoleWindow("Overwriting old " & sFile & " in " & destDir)
                    End If

                End Try
            Next i
        End Sub
    LVL 4

    Author Comment

    Yeah I am using 2003. I read about that feature.  I found somthing that will work.  I will give you the points because you responded, and I dont want to delete the question because other might find it useful.

    LVL 6

    Expert Comment

    Try this:-

                'Stores Directory List
                Dim ListBox1 As New ListBox

                'Stores File List
                Dim ListBox2 As New ListBox

                ' Directory to start search for files
                Dim strDir As String = "C:\"

                ' Store Directories

                ' Get .txt files for main directory
                ListBox2.Items.AddRange(System.IO.Directory.GetFiles(strDir, "*.txt"))

                ' Get .txt Files in each sub-directory of main directory
                For i As Integer = 0 To ListBox1.Items.Count - 1

                    ' Select Directory
                    ListBox1.SelectedIndex = i

                    ' Add files to list
                        ListBox2.Items.AddRange(System.IO.Directory.GetFiles(ListBox1.SelectedItem.ToString(), ".txt"))
                    Catch ex As Exception

                    End Try


                ' Location to copy files to
                Dim strLoc As String = "C:\Temp\"

                ' Copy files to new location
                ' Get .txt Files in each directory
                For i As Integer = 0 To ListBox2.Items.Count - 1

                    ' Select File
                    ListBox2.SelectedIndex = i

                    ' ' Store file name for copying
                    Dim strCopy As String = ListBox2.SelectedItem.ToString().Replace( _
                        IO.Directory.GetDirectoryRoot(ListBox2.SelectedItem.ToString()), "")

                    ' Create copy to
                    strCopy = strLoc & strCopy

                    ' Copy files to new location
                        System.IO.File.Copy(ListBox2.SelectedItem.ToString(), strCopy)
                    Catch ex As Exception


                        MsgBox("Failed to copy " & ListBox2.SelectedItem.ToString())

                    End Try


            Catch ex As Exception


            End Try
    LVL 4

    Author Comment

    Thanks willbdman but I got it.  Wish I could take back the acceptance and split the points.

    Featured Post

    Free Trending Threat Insights Every Day

    Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

    Join & Write a Comment

    Article by: Kraeven
    Introduction Remote Share is a simple remote sharing tool, enabling you to see, add and remove remote or local shares. The application is written in VB.NET targeting the .NET framework 2.0. The source code and the compiled programs have been in…
    I think the Typed DataTable and Typed DataSet are very good options when working with data, but I don't like auto-generated code. First, I create an Abstract Class for my DataTables Common Code.  This class Inherits from DataTable. Also, it can …
    Access reports are powerful and flexible. Learn how to create a query and then a grouped report using the wizard. Modify the report design after the wizard is done to make it look better. There will be another video to explain how to put the final p…
    This video gives you a great overview about bandwidth monitoring with SNMP and WMI with our network monitoring solution PRTG Network Monitor ( If you're looking for how to monitor bandwidth using netflow or packet s…

    746 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    14 Experts available now in Live!

    Get 1:1 Help Now