在C#中,要刪除非空文件夾及其內容,可以使用Directory.Delete
方法。這個方法會刪除指定的目錄及其所有子目錄和文件。這里有一個示例代碼:
using System;
using System.IO;
class Program
{
static void Main()
{
string folderPath = @"C:\example_folder";
try
{
if (Directory.Exists(folderPath))
{
Directory.Delete(folderPath, true); // 設置recursive參數為true以刪除非空文件夾
Console.WriteLine("文件夾已成功刪除。");
}
else
{
Console.WriteLine("文件夾不存在。");
}
}
catch (Exception ex)
{
Console.WriteLine("刪除文件夾時發生錯誤: " + ex.Message);
}
}
}
在這個示例中,我們首先檢查folderPath
是否存在。如果存在,我們使用Directory.Delete
方法刪除該文件夾,并將recursive
參數設置為true
。這將刪除文件夾及其所有子目錄和文件。如果在刪除過程中發生任何錯誤,我們將捕獲異常并顯示錯誤消息。