How to: Copy Files with a Specific Pattern to a Directory in Visual Basic
The 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 CopyFile method to copy the files to a directory.
To copy files with a specific pattern to a directory
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")
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))
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:
The path is not valid for one of the following reasons: it is a zero-length string, it contains only white space, it contains invalid characters, or it is a device path (starts with \\.\) (ArgumentException).
The path is not valid because it is Nothing (ArgumentNullException).
The directory does not exist (DirectoryNotFoundException).
The directory points to an existing file (IOException).
The path exceeds the system-defined maximum length (PathTooLongException).
A file or directory name in the path contains a colon (:) or is in an invalid format (NotSupportedException).
The user lacks necessary permissions to view the path (SecurityException). The user lacks necessary permissions (UnauthorizedAccessException).
See Also
Tasks
How to: Find Subdirectories with a Specific Pattern in Visual Basic
Troubleshooting: Reading from and Writing to Text Files (Visual Basic)
How to: Get the Collection of Files in a Directory in Visual Basic