Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Server.MapPath in MVC3

Tags:

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

like image 522
P.Brian.Mackey Avatar asked Sep 29 '11 16:09

P.Brian.Mackey


People also ask

What is the use of server MapPath?

Because the MapPath method maps a path regardless of whether the specified directories currently exist, you can use the MapPath method to map a path to a physical directory structure, and then pass that path to a component that creates the specified directory or file on the server.

What is Server MapPath returns?

If the path starts with either a forward slash(/) or backward slash(\) the MapPath Method returns a path as if the path is a full virtual path. If the path doesn't start with a slash, the MapPath Method returns a path relative to a directory of the . asp file being processed.


1 Answers

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.

like image 79
vcsjones Avatar answered Dec 13 '22 18:12

vcsjones