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

ASP.NET 檔案與資料夾操作工具類完整代碼

     編輯:關於ASP.NET

封裝 System.IO 常用操作,處理虛擬路徑轉換、例外吞噬、編碼指定,可直接引用專案。

核心類別:FileControl

using System;
using System.IO;
using System.Web;

namespace SEC
{
    public class FileControl
    {
        // 取得實體路徑輔助
        private string MapPath(string virtualPath)
        {
            return HttpContext.Current.Server.MapPath(virtualPath);
        }

        // 建立資料夾
        public void CreateFolder(string folderPath)
        {
            if (string.IsNullOrWhiteSpace(folderPath)) return;
            string phys = MapPath("~/Images/" + folderPath);
            if (!Directory.Exists(phys)) Directory.CreateDirectory(phys);
        }

        // 刪除資料夾及所有內容
        public void DeleteFolder(string folderPath)
        {
            if (string.IsNullOrWhiteSpace(folderPath)) return;
            string phys = MapPath(folderPath);
            if (Directory.Exists(phys)) Directory.Delete(phys, true);
        }

        // 刪除單一檔案
        public void DeleteFile(string filePath)
        {
            try { File.Delete(MapPath(filePath)); } catch { /* 記錄日誌 */ }
        }

        // 建立檔案(含父資料夾)
        public void CreateFile(string filePath)
        {
            string phys = MapPath(filePath);
            string dir = Path.GetDirectoryName(phys);
            if (!Directory.Exists(dir)) Directory.CreateDirectory(dir);
            if (!File.Exists(phys)) File.Create(phys).Close();
        }

        // 附加內容到檔案 (UTF-8)
        public void AppendText(string filePath, string text)
        {
            CreateFile(filePath);
            File.AppendAllText(MapPath(filePath), text, Encoding.UTF8);
        }

        // 讀取檔案全部文字
        public string ReadAllText(string filePath)
        {
            return File.ReadAllText(MapPath(filePath), Encoding.UTF8);
        }

        // 取得資料夾資訊
        public DirectoryInfo GetDirectoryInfo(string folderPath)
        {
            return new DirectoryInfo(MapPath(folderPath));
        }
    }
}

關鍵設計點

  • 統一使用 HttpContext.Current.Server.MapPath 解析虛擬路徑,支援 ~/ 根目錄語法。
  • 所有公開方法吞噬例外(建議改為記錄日誌再拋出或回傳 Result 物件)。
  • 編碼固定 UTF-8,避免中文亂碼。
  • CreateFile 自動建立父資料夾,呼叫端無需關心。

使用範例

var fc = new FileControl();
fc.CreateFolder("UserUploads/1001");
fc.AppendText("~/UserUploads/1001/log.txt", $"{DateTime.Now}: Upload OK\n");
string log = fc.ReadAllText("~/UserUploads/1001/log.txt");

生產環境擴充建議

  1. 引入 IFileStorage 介面,支援本地/Azure Blob/S3 切換。
  2. 大檔案採用 FileStream 分塊讀寫,避免記憶體壓力。
  3. 權限檢查:確保執行身分對目標路徑有讀寫權限。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved