Wednesday 15 June 2011

ASP: the Server.MapPath method

   


The Server.MapPath method is used to obtain the relative or virtual path to map a physical folder. How many times did we use it? Did we fully understand how it works?
Well, let's get into it and see.

The syntax
The basic syntax of the method is:
Server.MapPath(path)
where path is the relative or virtual path to map a physical folder. The parameter is required. When you use the method in an asp page, the page path will be affecting the output produced. If the path parameter start with a backslash or a slash, the method will return a path relative to the path where the asp page containing the method is located.


Examples
We assume that the file containing the method is located in C:\InetPub\Wwwroot\example. The file is called test.asp. If we use the method in the following way:
<%
response.write (Server.MapPath(".")) & "<br>"
response.write (Server.MapPath("..")) & "<br>"
response.write (Server.MapPath("/")) & "<br>"
response.write (Server.MapPath("\"))
%>
the result will be:
C:\InetPub\Wwwroot\example
C:\InetPub\Wwwroot
C:\InetPub\Wwwroot
C:\InetPub\Wwwroot
That will be more clear if we use different parameters:
<%
response.write (Server.MapPath("test.asp")) & "<br>"
response.write (Server.MapPath("\example"))
%>
The result will be:
C:\InetPub\Wwwroot\example\test.asp
C:\InetPub\Wwwroot\example

The rules
We can summarise the above examples with:
1) path = "filename", result = the path to the file;
2) path = ".", result = the current physical folder/directory without the trailing backslash;
3) path = "/", result = the physical root path;
4) path = "../filename.asp", result = the parent directory

0 thoughts:

Post a Comment

Comments are moderated. I apologize if I don't publish comments immediately.

However, I do answer to all the comments.