我和 Server.MapPath(). 。当我打电话时 Server.MapPath("~") 在我在ASP.NET开发服务器中运行的应用程序中,它返回的root Directory在后斜线中结束如 f:\projects\app1\, ,但我称其为已发布的版本,安装在IIS中,它返回根目录,而没有任何背斜线 c:\inetpub\wwwroot\app1. 。为什么会发生这种情况?如何避免?

我在同一台计算机上做了2个方案:Windows Server 2008 R2 X64,Visual Studio 2010 X64,IIS 7。

更新:

为什么我关心它? Ineed我已经根据文件/文件夹结构编写了自定义站点地图提供商。它提取根目录的文件/文件夹列表 "~", ,将根目录部分替换为 Server.MapPath("~") 为了生成URL .aspx 用于在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
    }
有帮助吗?

解决方案

它可能来自当您在IIS内部设置虚拟目录时,具体取决于您在设置时是否使用了Taild Slash。

但是真的很重要吗?你为什么要关心什么 Server.MapPath("~") 返回?我无法想象您会像那样使用它。更有可能的是,当您实际上需要通往某事的途径时 里面 你的申请:

Server.MapPath("~/Something/Foo.txt");

此外,每当您建立道路时,都应该尝试养成使用的习惯 path.combine, ,因为您根本不必担心拖曳斜线:

string fullPath = Path.Combine(Server.MapPath("~"), @"Something\Foo.txt");
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top