Recursively Listing And Copying Files

muabao

Member
Joined
Dec 20, 2007
Messages
6
Programming Experience
Beginner
Hi All,
I've done some searches but couldn't find anything. Here's what I'm trying to do:
- I want to recursively display all the files (pattern, for ex. *.txt is user-selected) for a given directory.
- The files are displayed in a ListBox but I only want to display the files' names, no directories.
- The user can single- or multiple-select the file(s) & then click the Copy button.
- The program should then copy all the selected file(s) to the destination directory.

Since I'm only displaying the files' names, I of course will run into the file-not-found problem.

How do you think I can pass the files' directory name sto the copy function without displaying them in the ListBox?

Attached is the zipped file.

Any help is greatly appreciated.

Thanks,
MB
 

Attachments

  • CopyFiles.zip
    12 KB · Views: 22
Last edited by a moderator:
When you're getting the filenames, if you store them in a List (Of String) you can simply pass the filename from the List based on the index of the listbox
 
With the GetFiles method of IO.DirectoryInfo you can search files recursively, it returns an array of IO.FileInfo objects. Bind the Listbox to this array and set DisplayMember to "Name". Example:
VB.NET:
Private Sub SearchButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SearchButton.Click
    Me.FolderBrowserDialog1.Description = "Select source folder"
    If Me.FolderBrowserDialog1.ShowDialog = Windows.Forms.DialogResult.OK Then
        Dim di As New IO.DirectoryInfo(Me.FolderBrowserDialog1.SelectedPath)
        ListBox1.DataSource = di.GetFiles("*.txt", IO.SearchOption.AllDirectories)
        ListBox1.DisplayMember = "Name"
    End If
End Sub

Private Sub CopyButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CopyButton.Click
    Me.FolderBrowserDialog1.Description = "Select destination folder"
    If Me.FolderBrowserDialog1.ShowDialog = Windows.Forms.DialogResult.OK Then
        For Each fi As IO.FileInfo In Me.ListBox1.SelectedItems
            fi.CopyTo(IO.Path.Combine(Me.FolderBrowserDialog1.SelectedPath, fi.Name))
        Next
    End If
End Sub
 
Back
Top