Afs*_*bbi 4 asp.net server.mappath
我有一个真正的噩梦Server.MapPath()
.当我调用Server.MapPath("~")
在ASP.NET Development Server中运行的应用程序时,它返回以反斜杠结尾的根目录f:\projects\app1\
,但我在发布的版本中调用它,安装在IIS中,它返回根目录而没有任何反斜杠c:\inetpub\wwwroot\app1
.为什么会这样?怎么可以避免?
我在同一台机器上做了两个场景:Windows Server 2008 R2 x64,Visual Studio 2010 x64,IIS 7.
更新:
我为什么关心它?Ineed我已经根据文件/文件夹结构编写了一个自定义站点地图提供程序.它提取根目录的文件/文件夹列表"~"
,替换根目录部分,Server.MapPath("~")
以生成.aspx
用于ASP.NET Menu
控件的文件的URL .我认为以下代码解释了我在做什么:
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
}
Run Code Online (Sandbox Code Playgroud)
它可能是从您在IIS中设置虚拟目录时开始,具体取决于您在设置时是否使用了斜杠.
但它真的重要吗?为什么你会关心什么Server.MapPath("~")
回报?我无法想象你会像那样使用它.更有可能的是,当您确实需要一条到应用程序内部的路径时:
Server.MapPath("~/Something/Foo.txt");
Run Code Online (Sandbox Code Playgroud)
此外,每当你构建路径时,你应该尝试养成使用Path.Combine的习惯,因为你根本不需要担心尾随斜杠:
string fullPath = Path.Combine(Server.MapPath("~"), @"Something\Foo.txt");
Run Code Online (Sandbox Code Playgroud)