| 相對路徑 | 對應實體路徑 |
|---|---|
"test.txt" | 當前目錄下的 test.txt |
"a/test.txt" | 當前目錄下子目錄 a 的 test.txt |
"../a/test.txt" | 當前目錄平級目錄 a 的 test.txt |
"~/a/test.txt" | 網站根目錄下子目錄 a 的 test.txt |
呼叫 Server.MapPath(相對路徑) 即可取得絕對路徑。
using System.IO;
private void Button1_Click(object sender, EventArgs e)
{
HttpPostedFile hpf = FileUpload1.PostedFile;
string fileName = Path.GetFileName(hpf.FileName);
string serverPath = Server.MapPath("~/");
hpf.SaveAs(serverPath + fileName);
}
關鍵點:Path.GetFileName 取得純檔名避免路徑遍歷攻擊;Server.MapPath("~/") 固定指向網站根目錄,不受虛擬目錄層級影響。