Udostępnij za pośrednictwem


How to: Copy Files with a Specific Pattern to a Directory in Visual Basic

The My.Computer.FileSystem.GetFiles Method returns a read-only collection of strings representing the path names for the files. You can use the wildCards parameter to specify a specific pattern.

An empty collection is returned if no matching files are found.

You can use the My.Computer.FileSystem.CopyFile Method to copy the files to a directory.

To copy files with a specific pattern to a directory

  1. Use the GetFiles method to return the list of files. This example returns all .rtf files in the specified directory.

    For Each foundFile As String In My.Computer.FileSystem.GetFiles( _
        My.Computer.FileSystem.SpecialDirectories.MyDocuments, _
        Microsoft.VisualBasic.FileIO.SearchOption.SearchTopLevelOnly, "*.rtf")
    
  2. Use the CopyFile method to copy the files. This example copies the files to the directory named testdirectory.

    My.Computer.FileSystem.CopyFile(foundFile, "C:\testdirectory\" & My.Computer.FileSystem.GetName(foundFile))
    
  3. Close the For statement with a Next statement.

    Next
    

Example

The following example, which presents the above snippets in complete form, copies all .rtf files in the specified directory to the directory named testdirectory.

For Each foundFile As String In My.Computer.FileSystem.GetFiles( _
    My.Computer.FileSystem.SpecialDirectories.MyDocuments, _
    Microsoft.VisualBasic.FileIO.SearchOption.SearchTopLevelOnly, "*.rtf")

    My.Computer.FileSystem.CopyFile(foundFile, "C:\testdirectory\" & foundFile)
Next

Security

The following conditions may cause an exception:

See Also

Tasks

How to: Find Subdirectories with a Specific Pattern in Visual Basic

Troubleshooting: Reading from and Writing to Text Files

How to: Get the Collection of Files in a Directory in Visual Basic

Reference

My.Computer.FileSystem.CopyFile Method

My.Computer.FileSystem.GetFiles Method