Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HttpContext.Current.Server null

I have a windows service which is using a method from a class library with same asp.net solution. in class library, I have a method with following line:

 reader = XmlReader.Create(HttpContext.Current.Server
             .MapPath("~/TestDevice/Data.xml"), settings);

When control comes to this line. I get exception. I tried to debug the code and found that when service tries to access this method then HttpContext.Current.Server is null. What is alternative syntax.

I tried to access this class library method from web application and it works fine.

Please suggest solution.

like image 533
DotnetSparrow Avatar asked Jun 10 '11 09:06

DotnetSparrow


People also ask

Why HttpContext current is null?

Clearly HttpContext. Current is not null only if you access it in a thread that handles incoming requests. That's why it works "when i use this code in another class of a page".

What is Server MapPath in C#?

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


2 Answers

HttpContext.Current is returning null because your Windows Service is not running under the umbrella of IIS or some other web server provder.

However, you can find the executing path of your service using reflection:

System.Reflection.Assembly.GetExecutingAssembly().Location

^ should return the path of the executing service..

like image 179
The Evil Greebo Avatar answered Sep 19 '22 00:09

The Evil Greebo


This method works much better:

string baseDirectory = AppDomain.CurrentDomain.BaseDirectory;
like image 44
Lucia Minerba Avatar answered Sep 21 '22 00:09

Lucia Minerba