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

ASP.NET Server.MapPath 相對路徑對照表與檔案上傳實戰

     編輯:關於C#

Server.MapPath 核心規則

Server.MapPath("相對路徑") 將虛擬路徑(相對於網站根目錄或當前頁面)轉換為伺服器實體絕對路徑。回傳值以 \ 結尾(目錄)或含檔名。

相對路徑寫法對照表

相對路徑對應實體路徑說明
"test.txt"C:\Site\CurrentDir\test.txt當前頁面目錄下的檔案
"sub/test.txt"C:\Site\CurrentDir\sub\test.txt當前目錄下子資料夾
"../sibling/test.txt"C:\Site\ParentDir\sibling\test.txt父目錄下的同級資料夾
"~/app_data/test.txt"C:\Site\app_data\test.txt波浪號 ~ 代表網站根目錄,最推薦寫法
"/test.txt"C:\Site\test.txt根目錄(同 ~)

檔案上傳完整範例

// ASP.NET WebForms / MVC Controller 通用
public void UploadFile(HttpPostedFileBase file) // 或 HttpPostedFile
{
    if (file == null || file.ContentLength == 0) return;

    // 1. 取得純檔名(防止路徑遍歷攻擊)
    string fileName = Path.GetFileName(file.FileName);
    if (string.IsNullOrWhiteSpace(fileName)) return;

    // 2. 產生唯一檔名避免覆蓋
    string uniqueName = $"{Guid.NewGuid():N}_{fileName}";

    // 3. 目標資料夾:網站根目錄下的 Uploads
    string uploadFolder = Server.MapPath("~/Uploads/");
    if (!Directory.Exists(uploadFolder)) Directory.CreateDirectory(uploadFolder);

    string fullPath = Path.Combine(uploadFolder, uniqueName);

    // 4. 儲存
    file.SaveAs(fullPath); // HttpPostedFileBase
    // file.SaveAs(fullPath); // HttpPostedFile 同樣方法
}

安全性檢查清單

  • ✅ 檔名純化:Path.GetFileName 移除目錄資訊,防止 ../../etc/passwd。
  • ✅ 副檔名白名單:僅允許 .jpg、.pdf、.xlsx 等。
  • ✅ MIME 驗證:檢查 file.ContentType,防止偽裝副檔名。
  • ✅ 檔案大小限制:web.config 設定 maxRequestLength / maxAllowedContentLength。
  • ✅ 儲存路徑隔離:上傳資料夾設定 web.config 禁止執行腳本(<handlers accessPolicy="Read" />)。
  • ✅ 病毒掃描:生產環境整合 ClamAV 或雲端掃描 API。

ASP.NET Core 対應寫法

// IWebHostEnvironment 注入
public class FileService
{
    private readonly IWebHostEnvironment _env;
    public FileService(IWebHostEnvironment env) => _env = env;

    public string SaveUpload(IFormFile file)
    {
        string uploads = Path.Combine(_env.WebRootPath, "uploads");
        Directory.CreateDirectory(uploads);
        string fileName = $"{Guid.NewGuid():N}_{Path.GetFileName(file.FileName)}";
        string fullPath = Path.Combine(uploads, fileName);
        using (var fs = new FileStream(fullPath, FileMode.Create))
            file.CopyTo(fs);
        return $"/uploads/{fileName}"; // 回傳相對 URL
    }
}

常見錯誤與解決

錯誤原因解決
路徑包含 .. 導致跳出網站根目錄未驗證使用者輸入路徑永遠用 Path.GetFileName 取純檔名,自行組合路徑
權限不足:Access deniedIIS_IUSRS / ApplicationPoolIdentity 無寫入權限給上傳資料夾寫入權限,或用 App_Data 目錄(預設有權限)
大檔上傳失敗 (404/413)預設限制 4MB / 30MB調整 web.config maxRequestLength (KB) / maxAllowedContentLength (Bytes)

總結

Server.MapPath("~/...") 是 ASP.NET 經典專案處理實體路徑的標準方式,關鍵在於善用波浪號 ~ 代表網站根目錄,避免相對路徑在不同頁面層級下解析不一致。檔案上傳務必落實檔名純化、副檔名白名單、權限隔離、大小限制四大防護。ASP.NET Core 改用 IWebHostEnvironment.WebRootPath / ContentRootPath,邏輯一致、API 更現代。

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