Saturday, July 14, 2007

From time to time, there is a need to get something from a file system in our ASP.NET applications. In those cases, we use the Server.MapPath() call on our pages classes. But what about class libraries?

Usually in class libraries in order to get the physical path of a file on disk we can use something like HttpContext.Current.Server.MapPath() and it works as long as there is a context i.e.: HttpContext.Current is not null. Sometimes however it may happen that there is a task running on the server which does some work without any request being processed. What then?

Enter the HostingEnvironment.MapPath() method where HostingEnvironment is a class defined in System.Web.Hosting namespace. It works the same way, as Server.MapPath() but it is a static method requiring no context to be present.

Tuesday, July 31, 2007 8:18:53 PM (Central European Standard Time, UTC+01:00)
Great!
Good note.
Friday, August 31, 2007 8:55:27 PM (Central European Standard Time, UTC+01:00)
Fantastic! Thank you for sharing this, I recently had a NullReferenceException in my log file and it turns out it was from using HttpContext.Current.Server.MapPath(). That's a damn useful namespace (System.Web.Hosting).

Thanks again...
Name
E-mail
Home page

Comment (Some html is allowed: a@href@title, strike) where the @ means "attribute." For example, you can use <a href="" title=""> or <blockquote cite="Scott">.  

Enter the code shown (prevents robots):

Live Comment Preview