Using Server.MapPath in MVC3

P.Brian.Mackey picture P.Brian.Mackey · Sep 29, 2011 · Viewed 50.1k times · Source

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

Answer

vcsjones picture vcsjones · Sep 29, 2011

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.