首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> ASP.NET 基礎 >> 關於ASP.NET

ASP.NET 網絡硬盤實作 (四):檔案與資料夾刪除

     編輯:關於ASP.NET

刪除功能實作

protected void btnDelete_Click(object sender, EventArgs e)
{
 if (lbFiles.SelectedIndex < 0) return;
 string selected = lbFiles.SelectedValue;

 // 安全性檢查
 if (!IsPathSafe(selected, RootPath)) { lblMsg.Text = "非法路徑"; return; }

 try
 {
 if (Directory.Exists(selected))
 {
 Directory.Delete(selected, true); // true = 遞迴刪除子目錄與檔案
 lblMsg.Text = "資料夾已刪除";
 }
 else if (File.Exists(selected))
 {
 File.Delete(selected);
 lblMsg.Text = "檔案已刪除";
 }
 else
 {
 lblMsg.Text = "項目不存在";
 }
 LoadDirectory(CurrentPath);
 }
 catch (IOException ex)
 {
 lblMsg.Text = "刪除失敗 (檔案可能被鎖定): " + ex.Message;
 }
 catch (UnauthorizedAccessException ex)
 {
 lblMsg.Text = "權限不足: " + ex.Message;
 }
 catch (Exception ex)
 {
 lblMsg.Text = "刪除失敗: " + ex.Message;
 }
}

進階:軟刪除 (回收桶)

避免誤刪資料永久遺失,建議實作軟刪除:

  1. 資料庫表 `DeletedItems`:`Id, OriginalPath, DeletedBy, DeletedTime, IsFolder, Size`。
  2. 刪除時:移動至 `RecycleBin\{UserId}\{Guid}` 目錄,寫入資料庫記錄。
  3. 提供「回收桶」頁面:列出已刪項目、還原、永久刪除、清空。
  4. 定期清理:排程作業刪除超過 30 天的回收桶項目。

資料夾刪除效能優化 (大量檔案)

  • `Directory.Delete(path, true)` 遞迴刪除大量檔案極慢且易超時。
  • 改用非同步佇列:記錄刪除任務 → 背景服務 (Hangfire/Windows Service) 執行 `cmd /c rmdir /s /q` 或 `System.IO` 分批刪除。
  • 前端顯示「刪除中...」,輪詢任務狀態。

批次刪除 (多選)




protected void btnBatchDelete_Click(object sender, EventArgs e)
{
 foreach (ListItem item in lbFiles.Items)
 {
 if (item.Selected)
 {
 string path = item.Value;
 if (IsPathSafe(path, RootPath))
 {
 try
 {
 if (Directory.Exists(path)) Directory.Delete(path, true);
 else if (File.Exists(path)) File.Delete(path);
 }
 catch { /* 記錄失敗 */ }
 }
 }
 }
 LoadDirectory(CurrentPath);
}

總結

刪除操作看似簡單,實則涉及安全性 (路徑遍歷)、效能 (大量檔案)、使用者體驗 (軟刪除/回收桶)、併發 (檔案鎖定)。生產環境務必實作軟刪除、背景非同步刪除、完整稽核日誌。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved