Using Server.MapPath() in ASP
When configuring ASP scripts or writing new ones, it's often necessary to find the physical path to some file or database on your server. This is especially true if you're ever using the FileSystemObject (FSO). Unfortunately, unlike friendly virtual paths (i.e. /database/users.mdb), physical paths are often hard to remember (i.e. C:\websites\12.34.567.890\domain.com\database\users.mdb). Luckily, there's a really simple way to find the physical path to a file, as long as you know the virtual path. To do this, we take advantage of the Server.MapPath() function.
Usage
If there was a database in the virtual location /database/users.mdb on your site, you can easily find the physical path like this:
<% physicalpath = Server.MapPath("/database/users.mdb") response.write physicalpath %>
The code above writes out the physical path to the file you feed to Server.MapPath().
Often we need to find our way around the directory structure of a website, and this can be accomplished using Server.MapPath() as well.
Path to Current Directory:
<% currentDir = Server.MapPath("./.") %>
Path to Parent Directory:
<% parentDir = Server.MapPath("../") %>
Path to Root Directory: (i.e. yoursite.com)
<% rootDir = Server.MapPath("/") %>
Finding the Path to the Script
Another common task is finding the physical path to the current ASP file you're working with. We can obtain the virtual path to our current ASP file using:
<% VirPath = Request.ServerVariables("PATH_INFO") %>
i.e. /users/username/public_html/scripts/script.asp
Feeding that virtual path into Server.MapPath() gives us the desired physical path to our current ASP file:
<% PhyPath = Server.MapPath(Request.ServerVariables("PATH_INFO")) %>
Conclusion
Once you get use to using it, you'll find that Server.MapPath() will save you a lot of time and hassle.
- 307 reads

