Home
    Shop
    Advertise
    Write For Us
    Affiliate
    Newsletter
    Contact

Using Server.MapPath in ASP.NET

Uses of Server.MapPath

Server.MapPath function is used whenever physical location of file or folder is needed. MapPath expects one parameter, a virtual or relative path to file or folder, and returns corresponding physical absolute path on the server. Although we can use absolute paths directly, that's not adjustable and is considered as hard to maintain. For example, let say you want to allow users to upload their images to website, and store images in sub folder /images. But, FileUpload will not accept relative "/images" path. FileUpload control requires absolute path on server, a physical location on disc where image will be saved. To make upload work, you have to provide absolute path on server in form like "D:\wwwroot\mysite\htdocs\images\".

Although you can set this path somewhere in application settings or even hard coded, it is much easier to work with relative paths and use Server.MapPath function. Syntax Server.MapPath("/images") will translate given relative path to real physical path on disc. In this case relative path to folder "/images" becomes "D:\wwwroot\mysite\htdocs\images\". Same like folders, Server.MapPath works with files too. For example, for relative path to file Server.MapPath("/data/user-settings.xml") will return something like "D:\wwwroot\mysite\htdocs\data\user-settings.xml" and so on.

Using Server.MapPath with special characters

In addition to letters and numbers, there are few characters with special meaning in Server.MapPath:

Server.MapPath("/") or Server.MapPath("\") - starting / represents root folder of domain name
Server.MapPath("~") - returns root application folder, often same as domain name folder. It's same as Request.PhysicalApplicationPath.
Server.MapPath(".") or Server.MapPath("") or Server.MapPath(Null) - returns current folder, the folder where current page is located. This is default behaviour, if you send empty string or Null value as a parameter, MapPath returns current folder.
Server.MapPath("..") or Server.MapPath("../") or Server.MapPath("..\") - retrieves parent directory, the directory one level above of current directory. On same way, "../../" returns two levels up and so on.

How to get physical path of current ASP.NET page

You can use PATH_INFO server variable to get physical path of current page. Code could look like this:

[ C# ]

string pagePath = Server.MapPath(Request.ServerVariables("PATH_INFO"));

[ VB.NET ]

Dim pagePath As String = Server.MapPath(Request.ServerVariables("PATH_INFO"))

Limitation of Server.MapPath function

Server.MapPath works only inside of root folder of web application. You can't use it outside, for example if page is already in root folder and you try Server.MapPath("../"), server will return an error: Cannot use a leading .. to exit above the top directory.

Server.MapPath, cannot use a leading .. to exit above the top directory

MapPath in Global.asax, App_Code classes, WCF, .ashx, dlls etc.

Since Server object is just a property of Page, so if called from Master Page, Server.MapPath will return location of current page. But, we can't use Server.MapPath function outside of page's code. If you try to sue Server.MapPath function in class module, you will get next error:

Error. "The name 'Server' does not exist in the current context"

To resolve the problem, instead of Server.MapPath, one option is to use static method System.Web.HttpContext.Current.Server.MapPath(). This works in some cases, but what to do if you don't have Context? If you don't have HttpContext instance, like in business layer dlls or Application_Start() procedure in Global.asax, there is more convenient static method which works everywhere:
System.Web.Hosting.HostingEnvironment.MapPath("/")

HostingEnvironment.MapPath will work from any place in web application, but it has some quirks in input parameter. For example, you can't use "." to get current folder, an empty string "", can't use ".." for parent folder or "subFolder/nextSubFolder" to get sub folders. Instead of relative paths, with HostingEnvironment.MapPath you can use only absolute syntax which starts with "/" or "~/" which start in domain or application root folder.

Difference between Server.MapPath and Request.MapPath

Server.MapPath calls Request.MapPath inside, so they are practically same. They both return same result, so it's only your personal preference which one to use. I use Server since it's one letter shorter than Request :).

Opposite Server.MapPath function

Sometimes you want to get virtual path from given physical path. Unfortunately, ASP.NET doesn't have a function which would do opposite of Server.MapPath. But, task is not so difficult, we have to only remove root folder part and turn slashes to right side. Function getVirtualPath could look like this:

[ C# ]

string getVirtualPath(string physicalPath)
{
   string applicationPath = Request.PhysicalApplicationPath;

   return physicalPath.Replace(applicationPath, "~/").Replace("\\", "/");
}

[ VB.NET ]

Function getVirtualPath(physicalPath As String) As String
   Dim applicationPath As String = Request.PhysicalApplicationPath

   Return physicalPath.Replace(applicationPath, "~/").Replace("\", "/")
End Function

Server.MapPath remarks

Server.MapPath is useful function that makes your application easier to maintain and to copy on other server without changes in configuration. When Server.MapPath is not available, use System.Web.Hosting.HostingEnvironment.MapPath which has a less options, but works from any part of web application.

You should know that Server.MapPath function is very slow, about 1000 times slower of string concatenation. It doesn't matter in most cases, but if your code calls Server.MapPath very frequently, you can consider caching of paths, or to keep application root path in variable and add relative paths to it.

Happy Coding!


Tutorial toolbar:  Tell A Friend  |  Add to favorites  |  Feedback  |   Google