Uredi

Deli z drugimi prek


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

  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

.NET Framework Security

The following conditions may cause an exception:

See also