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

Viewed 60117

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.

5 Answers

You can use something like the following piece of code. One thing to note is that I was facing an issue, where I was trying to access a .txt file from within a TestMethod and everything was failing except for this...and yeah it works for non-Unit Test Scenarios too.

string filePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory,@"..\..") + "\\email\\teste.html";

Issue: I had an "Images" folder inside a class library project. But using the above answers, I was not able to get the physical path of the folder to read/write the files inside that folder.

Solution: The below code worked for me to get a physical path in the class library project.

string physicalPath = System.IO.Path.GetFullPath("..\\..\\Images");

I hope, it will help someone who is facing the same issue as me.

Related