C# 刪除檔案並移動至資源回收筒

在 C# 中要刪除檔案非常簡單,只要一行:
    
File.Delete(@"C:\Users\ruyut\Desktop\file.txt");
    

不過和我們平時刪除檔案的習慣不一樣,這樣刪除的檔案並不會被移動到資源回收筒內,而是會直接永久刪除。

很遺憾的是並沒有內建移動到資源回收筒的刪除方式,如果要達成除了很麻煩的使用 Shell32.dll 以外,還可以使用 VB 的函式庫:
    
using Microsoft.VisualBasic.FileIO;

string path = @"C:\Users\ruyut\Desktop\file.txt";

if (File.Exists(path))
    FileSystem.DeleteFile(path, UIOption.OnlyErrorDialogs, RecycleOption.SendToRecycleBin);
    

只是和 File.Delete 相比,VB 的 FileSystem.DeleteFile 在沒有找到檔案的時候會拋出 System.IO.FileNotFoundException 例外,所以可以視情況加上 File.Exists 用來判斷檔案是否存在。

參考資料:
Microsoft.Learn - FileSystem.DeleteFile Method

留言