Tuesday, 25 November 2014

HostingEnvironment.MapPath() Vs Server.MapPath()



Note : The only difference is that you are allowed to pass null to Server.MapPath(), but not to HostingEnvironment.MapPath()

Use Server.MapPath()

Server.MapPath is used to map a physical location on webserver for asp.net.
String path = HttpContext.Current.Server.MapPath("~/myFolder/myFile.txt");

Server.MapPath specifies the relative or virtual path to map to a physical directory.
  • Server.MapPath(".")1 returns the current physical directory of the file (e.g. aspx) being executed
  • Server.MapPath("..") returns the parent directory
  • Server.MapPath("~") returns the physical path to the root of the application
  • Server.MapPath("/") returns the physical path to the root of the domain name (is not necessarily the same as the root of the application)




Use HostingEnvironment.MapPath

When running a service under IIS, the HttpContext.Current object is not available, so HttpContext.Current.Server.MapPath will fail.

fileName = HttpContext.Current.Server.MapPath(fileName);

The solution is to use Hosting.HostingEnvironment.MapPath instead.

fileName = System.Web.Hosting.HostingEnvironment.MapPath(fileName);



Like This also.....
using System.Web.Hosting;
String path = HostingEnvironment.MapPath("~/myFolder/myFile.txt");



No comments:

Post a Comment