Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 235
soamazing Avatar asked Jul 28 '11 15:07

soamazing


People also ask

What is Server MapPath in C#?

The MapPath method maps the specified relative or virtual path to the corresponding physical directory on the server.


2 Answers

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"); 
like image 64
nickytonline Avatar answered Oct 08 '22 07:10

nickytonline


if the code is not running from within a thread is executing a httprequest then HttpContext.Current is null (for example when you method is called via BeginInvoke) - see http://forums.asp.net/t/1131004.aspx/1 .

You can always use HttpRuntime see http://msdn.microsoft.com/en-us/library/system.web.httpruntime.aspx

like image 28
Yahia Avatar answered Oct 08 '22 07:10

Yahia