C# 完整刪除資料夾

C# 刪除指定檔案以及資料夾下的所有檔案的方法

因為在使用Directory.Delete(dir,true);會出錯,原因大概是因為裡面有檔案是唯讀狀態…

所以改使用以下程式碼來代替

動作說明 : 逐步刪除每一個檔案與資料夾

public static void DeleteFolder(string dir)
{
     foreach (string d in Directory.GetFileSystemEntries(dir))
     {
         if (System.IO.File.Exists(d))
         {
             FileInfo fi = new FileInfo(d);
             if (fi.Attributes.ToString().IndexOf("ReadOnly") != -1)
                 fi.Attributes = FileAttributes.Normal;
             System.IO.File.Delete(d);//直接删除其中的文件   
         }
         else
             DeleteFolder(d);//递归删除子文件夹   
     }
     Directory.Delete(dir);//删除已空文件夹   
}