使用 `System.IO.DirectoryInfo` / `FileInfo` 物件模型,遞歸處理每一層目錄,確保目的端目錄結構與來源完全一致。
Imports System.IO
Public Class DirectoryCopier
'''
''' 遞歸複製整個目錄樹
'''
''' 來源目錄
''' 目的地父目錄(將在其下建立同名子目錄)
Public Shared Sub CopyDirectory(sourceDir As DirectoryInfo, destDir As DirectoryInfo)
' 目的完整路徑 = 目的父目錄 \ 來源目錄名稱
Dim destPath As String = Path.Combine(destDir.FullName, sourceDir.Name)
' 建立目的目錄(若不存在)
If Not Directory.Exists(destPath) Then
Directory.CreateDirectory(destPath)
End If
' 複製當前層級所有檔案
For Each file In sourceDir.GetFiles()
Dim destFile = Path.Combine(destPath, file.Name)
File.Copy(file.FullName, destFile, overwrite:=True)
Next
' 遞歸處理子目錄
For Each subDir In sourceDir.GetDirectories()
Dim newDestDir As New DirectoryInfo(destPath)
CopyDirectory(subDir, newDestDir)
Next
End Sub
End Class
' 使用範例
Private Sub btnCopy_Click(sender As Object, e As EventArgs) Handles btnCopy.Click
Try
DirectoryCopier.CopyDirectory(
New DirectoryInfo("C:\Source\Data"),
New DirectoryInfo("D:\Backup")
)
MessageBox.Show("複製完成!")
Catch ex As Exception
MessageBox.Show($"錯誤:{ex.Message}")
End Try
End Sub
Public Delegate Sub ProgressCallback(copied As Long, total As Long, currentFile As String)
Public Shared Sub CopyDirectoryWithProgress(
sourceDir As DirectoryInfo,
destDir As DirectoryInfo,
Optional progress As ProgressCallback = Nothing,
Optional cancelToken As CancellationToken = Nothing)
Dim allFiles = sourceDir.GetFiles("*", SearchOption.AllDirectories)
Dim totalBytes = allFiles.Sum(Function(f) f.Length)
Dim copiedBytes = 0L
CopyRecursive(sourceDir, destDir, progress, cancelToken, copiedBytes, totalBytes)
End Sub
Private Shared Sub CopyRecursive(src As DirectoryInfo, dest As DirectoryInfo,
progress As ProgressCallback, cancelToken As CancellationToken,
ByRef copied As Long, total As Long)
If cancelToken.IsCancellationRequested Then Throw New OperationCanceledException()
Dim destPath = Path.Combine(dest.FullName, src.Name)
Directory.CreateDirectory(destPath)
For Each file In src.GetFiles()
cancelToken.ThrowIfCancellationRequested()
Dim destFile = Path.Combine(destPath, file.Name)
File.Copy(file.FullName, destFile, True)
copied += file.Length
progress?.Invoke(copied, total, file.Name)
Next
For Each subDir In src.GetDirectories()
CopyRecursive(subDir, New DirectoryInfo(destPath), progress, cancelToken, copied, total)
Next
End Sub
Private Shared Sub SafeCopy(source As String, dest As String, maxRetry As Integer)
For attempt = 1 To maxRetry
Try
File.Copy(source, dest, True)
Return
Catch ex As IOException When attempt < maxRetry
Thread.Sleep(200 * attempt) ' 指數退避
End Try
Next
Throw New IOException($"複製失敗經 {maxRetry} 次重試: {source}")
End Sub
public static void CopyDirectory(string source, string target)
{
Directory.CreateDirectory(target);
foreach (var file in Directory.GetFiles(source))
File.Copy(file, Path.Combine(target, Path.GetFileName(file)), true);
foreach (var dir in Directory.GetDirectories(source))
CopyDirectory(dir, Path.Combine(target, Path.GetFileName(dir)));
}
| 問題 | 原因 | 解決 |
|---|---|---|
| UnauthorizedAccessException | 權限不足(系統資料夾、網路磁碟) | Try-Catch 略過、以管理員執行、檢查 ACL |
| PathTooLongException | 路徑超過 260 字元 | 啟用長路徑支援 (Group Policy / .NET 4.6.2+)、使用 `\\?\` 前綴 |
| 檔案被鎖定 | 其他程序開啟中 | 重試機制、Volume Shadow Copy (VSS) |
| 符號連結/重新解析點 | 遞歸進入導致無限迴圈 | 檢查 `FileAttributes.ReparsePoint` 略過 |
遞歸複製目錄是經典檔案操作,掌握基本模式後,依專案需求加入進度、取消、錯誤重試、平行化等增強功能,即可建構生產級的檔案部署/備份工具。