在 C# 專案中,常需將整個資料夾結構(含子目錄與檔案)複製到目標路徑。.NET Framework 未直接提供單一 API 完成此任務,需自行實作遞歸邏輯。
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));
}
// 若為檔案則直接複製(覆寫同名檔案)
else
{
File.Copy(file, aimPath + Path.GetFileName(file), true);
}
}
}
catch (Exception ex)
{
// 建議記錄日誌後再拋出,避免靜默失敗
throw;
}
}
Path.DirectorySeparatorChar,跨平台相容。GetFileSystemEntries 回傳空陣列時自然結束。File.Copy 第三參數 true 允許覆寫既有檔案。throw 保留堆疊追蹤,上層可統一處理或記錄。IProgress<T>)以支援 UI 顯示。CancellationToken 支援取消操作。Parallel.ForEach 平行化複製(注意 I/O 瓶頸)。Directory.Copy(社群擴充套件)簡化程式碼。掌握遞歸複製資料夾的核心邏輯,並注意路徑處理與例外管理,即可在專案中靈活應用。建議依專案需求擴充進度通知與取消機制,提升使用者體驗。