封裝 System.IO 常用操作,處理虛擬路徑轉換、例外吞噬、編碼指定,可直接引用專案。
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 解析虛擬路徑,支援 ~/ 根目錄語法。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");
IFileStorage 介面,支援本地/Azure Blob/S3 切換。FileStream 分塊讀寫,避免記憶體壓力。