Friday, January 11, 2008

Server.MapPath Method

Server.MapPath is a function that takes one argument, a virtual path on the Web server, and returns the corresponding physical path.

This function can be used in a number of ways.
First, you can use it to obtain the physical path of a particular web page. For example:
C#
string strFilePath;
strFilePath = Server.MapPath("/WebApp/myWebPage.aspx");


Visual Basic
Dim strFilePath As String
strFilePath = Server.MapPath("/WebApp/myWebPage.aspx")


The output would depend on the web site's physical root directory, but it might be something like: "C:\Inetpub\wwwroot\WebApp\myWebpage.aspx".

You also can use this method to obtain the physical path of a particular directory. For example:
C#
//current directory
string strCurrDir = Server.MapPath("");
//parent directory
string strParentDir = Server.MapPath("..");
//root directory

string strRootDir = Server.MapPath("/");

Visual Basic
'current directory
Dim strCurrDir As String = Server.MapPath("")
'parent directory
Dim strParentDir As String = Server.MapPath("..")
'root directory

Dim strRootDir As String = Server.MapPath("/")

Whether you use backslahed (\) or forward slashes (/), it is same in this function. If you do not put a forward or backward slash at the beginning of the string passed into Server.MapPath, the current directory that the ASP page is being executed is used as the base for the physical path. Else, the root physical path is used as the base for the physical path. For example:
C#
string strFilePath1 = Server.MapPath("someXmlFile.xml");
string strFilePath2 = Server.MapPath("/someXmlFile.xml");

Visual Basic
Dim strFilePath1 As String = Server.MapPath("someXmlFile.xml")
Dim strFilePath2 As String = Server.MapPath("/someXmlFile.xml")


The two lines code above is executed in a ASP page running in the /Dir directory, where the page had physical path C:\Inetpub\wwwroot\Dir. So, the value of strFilePath1 and strFilePath2 will not be the same, where the value of strFilePath1 is C:\Inetpub\wwwroot\Dir\someXmlFile.xml and the value of strFilePath2 is C:\Inetpub\wwwroot\someXmlFile.xml.

Note:
To use MapPath function in a code-behind module, use HttpContext.Current.Server.MapPath.

1 comments:

Anonymous said...

Just wanted to add a comment that another way to go to the root directory is to use "~". for example use Server.Mappath("~")