Using Server.MapPath in MVC3

廉价感情. 提交于 2019-11-30 11:03:53

问题


I have the code

string xsltPath = System.Web.HttpContext.Current.Server.MapPath(@"App_Data") + "\\" + TransformFileName

It returns

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

Why am I getting the path to the ServiceController, SERVICENAME? I want the path to App_Data which is in

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


回答1:


You need to specify that you want to start from the virtual root:

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

Additionally, it's better practice to use Path.Combine to combine paths rather than concatenate strings. Path.Combine will make sure you won't end up in a situation with double-path separators.

EDIT:

Can you define "absolute" and "relative" paths and how they compare to "physical" and "virtual" paths?

MSDN has a good explanation on relative, physical, and virtual paths. Take a look there.




回答2:


The answers given so far are what you are looking for, but I think, in your particular case, what you actual need is this:

AppDomain.CurrentDomain.GetData("DataDirectory").ToString()

This will still return the file path to the App_Data directory if that directory name changes in future versions of MVC or ASP.NET.




回答3:


Try doing like this (@"~/App_Data"). ~/ represents the root directory.



来源:https://stackoverflow.com/questions/7600118/using-server-mappath-in-mvc3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!