Server.MapPath() 是 ASP.NET 中一个很常用的方法,用来将虚拟路径(相对于网站根目录的路径)转换为服务器上的物理路径

换句话说,它帮你把类似 /images/logo.png 这种“网站路径”转换成磁盘上的实际路径,比如 C:\inetpub\wwwroot\MyWeb\images\logo.png


1. 基本语法

string physicalPath = Server.MapPath(string virtualPath);
  • virtualPath:网站中的虚拟路径,可以是相对路径或绝对路径。
  • 返回值:物理路径(字符串)。

2. 常见用法示例

2.1 根目录路径

string path = Server.MapPath("~/"); 
// 返回网站根目录在磁盘上的物理路径

2.2 子目录路径

string imgPath = Server.MapPath("~/images/logo.png");
// 可能返回:C:\inetpub\wwwroot\MyWeb\images\logo.png

2.3 相对当前文件路径

string relativePath = Server.MapPath("data/file.txt");
// 如果当前页面在 /admin/ 下,会返回该页面所在目录的物理路径 + data/file.txt

2.4 上级目录

string upOneFolder = Server.MapPath("../config.xml");

3. 注意事项

  1. ~ 表示网站的根目录。
  2. 不要直接拼接用户输入的路径,避免路径遍历攻击。
  3. ASP.NET Core 中已经没有 Server.MapPath(),要用: var path = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "images", "logo.png"); 或通过注入 IWebHostEnvironmentWebRootPathContentRootPath

4. 实际场景

  • 保存文件上传的位置: string savePath = Server.MapPath("~/uploads/"); FileUpload1.SaveAs(Path.Combine(savePath, FileUpload1.FileName));
  • 读取配置文件: string configPath = Server.MapPath("~/App_Data/config.json"); string json = File.ReadAllText(configPath);