【发布时间】:2010-07-01 05:53:37
【问题描述】:
我和Server.MapPath() 做了一场真正的噩梦。当我在 ASP.NET 开发服务器中运行的应用程序中调用 Server.MapPath("~") 时,它返回以反斜杠结尾的根目录,如 f:\projects\app1\,但我在已发布的版本中调用它,安装在 IIS 中,它返回的根目录没有任何反斜杠,如c:\inetpub\wwwroot\app1。为什么会发生这种情况?怎么可能避免?
我在同一台机器上做了 2 个场景:Windows Server 2008 R2 x64、Visual Studio 2010 x64、IIS 7。
更新:
我为什么关心它?确实,我已经编写了一个基于文件/文件夹结构的自定义站点地图提供程序。它提取根目录"~" 的文件/文件夹列表,用Server.MapPath("~") 替换根目录部分,以生成.aspx 文件的URL 用于ASP.NET Menu 控件。我认为以下代码解释了我在做什么:
string mainRoot = HttpContext.Current.Server.MapPath("~");
DirectoryInfo di = new DirectoryInfo(mainRoot);
//added to solve this problem with Server.MapPath
if (!mainRoot.EndsWith(@"\"))
mainRoot += @"\";
FileInfo[] files = di.GetFiles("*.aspx");
foreach (FileInfo item in files)
{
string path = item.FullName.Replace(mainRoot, "~/").Replace(@"\", "/");
//do more here
}
【问题讨论】: