Share via


HOW TO:在 Visual Basic 中將具有特定模式的檔案複製到目錄

更新:2007 年 11 月

My.Computer.FileSystem.GetFiles 方法會傳回代表檔案的路徑名稱之字串的唯讀集合。您可以使用 wildCards 參數,指定特定的模式。

如果找不到相對應的檔案,則傳回空集合。

您可以使用 My.Computer.FileSystem.CopyFile 方法,將檔案複製到目錄。

若要將具有特定模式的檔案複製到目錄

  1. 使用 GetFiles 方法,傳回檔案清單。這個範例會傳回指定之目錄中的所有 .rtf 檔。

    For Each foundFile As String In My.Computer.FileSystem.GetFiles( _
        My.Computer.FileSystem.SpecialDirectories.MyDocuments, _
        FileIO.SearchOption.SearchTopLevelOnly, "*.rtf")
    
  2. 使用 CopyFile 方法,複製檔案。這個範例會將檔案複製到名為 testdirectory 的目錄。

    My.Computer.FileSystem.CopyFile(foundFile, "C:\testdirectory\" & foundFile)
    
  3. 以 Next 陳述式 (Statement) 關閉 For 陳述式。

    Next
    

範例

以下範例會將上述程式碼片段整理為完整格式,可複製指定之目錄中的所有 .rtf 檔,再傳送至名為 testdirectory 的目錄。

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

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

安全性

下列情形可能會造成例外狀況:

請參閱

工作

HOW TO:在 Visual Basic 中尋找具有特定模式的子目錄

疑難排解:讀取和寫入文字檔

HOW TO:在 Visual Basic 中取得目錄的檔案集合

參考

My.Computer.FileSystem.CopyFile 方法

My.Computer.FileSystem.GetFiles 方法