[C#] 遍歷指定資料夾並刪除指定副檔名的檔案

2023/10/11閱讀時間約 4 分鐘

當您需要使用 C# 程式語言來遍歷指定資料夾並刪除指定副檔名的檔案時,這篇教學將引導您完成這個任務。這個程式將使用遞迴方法,以確保不僅刪除指定資料夾中的檔案,還將刪除其所有子資料夾中符合條件的檔案。

引入必要的命名空間

FileDeleter.cs 檔案中,引入必要的命名空間,以便使用檔案和資料夾操作函式。

using System;
using System.IO;

建立 FileDeleter 類別

建立一個名為 FileDeleter 的 C# 類別,並在其中加入靜態方法 DeleteFilesByExtensionRecursively,該方法用於遞迴刪除指定副檔名的檔案。

class FileDeleter
{
public static void DeleteFilesByExtensionRecursively(string folderPath, string fileExtension)
{
if (!Directory.Exists(folderPath))
{
Console.WriteLine("指定的資料夾路徑不存在。");
return;
}

try
{
string[] files = Directory.GetFiles(folderPath, $"*.{fileExtension}");
foreach (string file in files)
{
File.Delete(file);
Console.WriteLine($"刪除檔案: {file}");
}

string[] subdirectories = Directory.GetDirectories(folderPath);
foreach (string subdirectory in subdirectories)
{
DeleteFilesByExtensionRecursively(subdirectory, fileExtension);
}
}
catch (Exception ex)
{
Console.WriteLine($"刪除檔案時發生錯誤: {ex.Message}");
}
}
}

建立 Main 方法

建立 Program 類別和 Main 方法,這將是您程式的入口點。在 Main 方法中,您將呼叫 DeleteFilesByExtensionRecursively 方法,並傳入資料夾路徑和副檔名,以開始刪除符合條件的檔案。

class Program
{
static void Main()
{
string folderPath = "資料夾路徑"; // 請替換為您的資料夾路徑
string fileExtension = "副檔名"; // 請替換為您要刪除的副檔名

FileDeleter.DeleteFilesByExtensionRecursively(folderPath, fileExtension);
}
}

執行程式

最後,您可以在您的 C# 開發環境中建置和執行這個程式。請確保替換 資料夾路徑副檔名 爲您的實際需求。當您執行程式時,它將遞迴遍歷指定資料夾及其子資料夾,並刪除指定副檔名的檔案。

請謹慎操作,因為刪除的檔案無法復原。這個程式是一個實用的工具,可以幫助您管理資料夾中的檔案。

51會員
101內容數
這裡將以輕鬆風格,深入探討程式設計的基礎和高級概念。從程式語言到演算法,我們將以易懂的方式解釋每個主題,讓你輕鬆掌握。無論你是初學者或有經驗者,都能在這裡找到適合你的內容。無論你的目標是成為專業開發者還是擴展知識,我們都會陪伴你一同成長!
留言0
查看全部
發表第一個留言支持創作者!