需刪除資料夾 d://test 內所有內容,但保留 system.ini 檔案。直接呼叫 DirectoryInfo.Delete(true) 會連帶刪除該檔案,需自訂刪除邏輯。
遞迴遍歷資料夾與檔案,僅刪除不符合保留條件的項目:
DirectoryInfo info = new DirectoryInfo(path);
// 刪除所有子資料夾
foreach (DirectoryInfo d in info.GetDirectories())
d.Delete(true);
// 刪除檔案,排除 system.ini
foreach (FileInfo f in info.GetFiles())
if (f.Name != "system.ini")
f.Delete();
HashSet<string> 以便擴充多檔案保留。此做法靈活且易維護,適合需精細控制刪除範圍的場景。