Using Server.MapPath in external C# Classes in ASP.NET

Chet picture Chet · Jul 27, 2009 · Viewed 227.1k times · Source

I'm trying to get the absolute path of certain files in a C# class. Server.MapPath works great of course for ASPX and their code-behind pages, but that doesn't exist in another class file. I tried HostingEnvironment.MapPath(), but that complains that the relative virtual path isn't allowed. Any thoughts?

System.Web is already imported.

Answer

womp picture womp · Jul 27, 2009

The ServerUtility class is available as an instance in your HttpContext. If you're in an environment where you know it'll be executed inside the ASP.Net pipeline, you can use

HttpContext.Current.Server.MapPath()

You'll have to import System.Web though.