In general whenever we need to get physical location of the file in ASP.Net Application, we use Server.MapPath. This is the most commonly adopted method. If you want the file to be located with reference to the path of the current WebPage, then the implementation holds good, but, in case you have to always refer the file from the application root, this method gives you different results. Take the following scenario, where the application directory structure is as follows:
- ClassA.cs (uses Server.MapPath(“\Data\Data.XML”))
- ClassB.cs (uses ClassA to get the XML file contents)
- ClassC.cs (uses ClassA to get the XML file contents)
In the above scenario the ClassC will fail to retrive the contents in case of the WebApplication is hosted in a virtual directory. The application will work fine if it is a website. So the implementation will not show any errors when we run the application from the Visual Studio. to make it more generic we can replace the Server.MapPath with
System.Web.Hosting.HostingEnvironment.ApplicationPhysicalPath + @”Data\Data.XML”.
2 thoughts on “Server.MapPath”
A wonderful job. Super helpful infotrmaion.
Woah nelly, how about them alpeps!