Accessing HttpContext objects from other classes

I could swear I wrote about this at some point in the distant past, but I couldn't find the article this week when I needed it to help troubleshoot an issue with another developer. The issue he was having was how to access objects from the executing web page's HttpContext object from a class other than the CodeBehind of the executing web-forms page. Essentially he was looking for a way to map a web-path to a physical folder path without needing to hard-code it or know where the application was deployed on the server in question.

If done correctly, an application can reside anywhere in the file system and be deployed to a virtual directory at any depth without causing a problem with URL resolution. In the code-behind of a web-forms page, the code is simple:

string physicalPath = Server.MapPath("~/somefolder/myfile.xml");

However doing this from another page involves just a little bit more work:

Using System.Web; string physicalPath = HttpContext.Current.Server.MapPath("~/somefilder/myfile.xml");

It's really quite straightforward when you see it, and I can't believe that I forget how to do it. This method will also provide you access to lots of other useful objects which makeup the "state" of the application from an HTTP perspective.