在MVC3中使用Server.MapPath

P.B*_*key 23 c# asp.net iis server.mappath asp.net-mvc-3

我有代码

string xsltPath = System.Web.HttpContext.Current.Server.MapPath(@"App_Data") + "\\" + TransformFileName
Run Code Online (Sandbox Code Playgroud)

它回来了

C:\inetpub\wwwroot\websiteName\SERVICENAME\App_Data\FileName.xsl

为什么我要获取ServiceController的路径SERVICENAME?我想要的App_Data路径

C:\inetpub\wwwroot\websiteName\App_Data\FileName.xsl

vcs*_*nes 57

您需要指定要从虚拟根目录开始:

string xsltPath = Path.Combine(System.Web.HttpContext.Current.Server.MapPath(@"~/App_Data"), TransformFileName);
Run Code Online (Sandbox Code Playgroud)

此外,最好使用Path.Combine组合路径而不是连接字符串.Path.Combine将确保你不会在双路分离器的情况下结束.

编辑:

您能定义"绝对"和"相对"路径以及它们与"物理"和"虚拟"路径的比较方式吗?

MSDN 对相对路径,物理路径和虚拟路径有很好的解释.看看那里.


Mat*_*ith 7

到目前为止给出的答案正是您所寻找的,但我认为,在您的具体情况下,您实际需要的是:

AppDomain.CurrentDomain.GetData("DataDirectory").ToString()
Run Code Online (Sandbox Code Playgroud)

如果在未来版本的MVC或ASP.NET中该目录名称发生更改,这仍将返回App_Data目录的文件路径.