以下方法 CopyDir 可完整複製來源目錄結構至目標路徑,包含子目錄與檔案,並自動建立不存在的目標資料夾:
private void CopyDir(string srcPath, string aimPath) {
try {
// 確保目標路徑以目錄分隔符結尾
if (aimPath[aimPath.Length - 1] != Path.DirectorySeparatorChar) {
aimPath += Path.DirectorySeparatorChar;
}
// 目標目錄不存在則建立
if (!Directory.Exists(aimPath)) {
Directory.CreateDirectory(aimPath);
}
// 取得來源目錄下所有檔案與子目錄
string[] fileList = Directory.GetFileSystemEntries(srcPath);
foreach (string file in fileList) {
// 若為目錄,遞迴複製
if (Directory.Exists(file)) {
CopyDir(file, aimPath + Path.GetFileName(file));
}
// 若為檔案,直接複製(true 覆蓋同名檔案)
else {
File.Copy(file, aimPath + Path.GetFileName(file), true);
}
}
}
catch (Exception e) {
throw; // 保留原始堆疊追蹤
}
}
srcPath:來源資料夾完整路徑(如 C:\\Data\\Source)aimPath:目標資料夾完整路徑(如 D:\\Backup\\Target)foreach 內擴充邏輯此實作利用 Directory.GetFileSystemEntries 同時取得檔案與目錄,配合遞迴處理,代碼簡潔且功能完整。