httpcontext.current.server.mappath Object reference not set to an instance of an object

soamazing picture soamazing · Jul 28, 2011 · Viewed 54k times · Source

I am using the following code within a class:

string filePath = HttpContext.Current.Server.MapPath("~/email/teste.html");

The file teste.html is in the folder

But when it will open the file the following error is being generated:

Object reference not set to an instance of an object.

Answer

nickytonline picture nickytonline · Jul 28, 2011

Don't use Server.MapPath. It's slow. Use this instead, HttpRuntime.AppDomainAppPath. As long as your web site is running, this property is always available to you.

Then use it like this:

string filePath = Path.Combine(HttpRuntime.AppDomainAppPath, "email/teste.html");