HttpContext.Current.Server null
Solution 1
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..
Solution 2
This method works much better:
string baseDirectory = AppDomain.CurrentDomain.BaseDirectory;
DotnetSparrow
I am working as asp.net freelance developer at eteksol. I have 7+ years of experience in asp.net/asp.net MVC/C#/SQl server.
Updated on September 14, 2022Comments
-
DotnetSparrow over 1 year
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
isnull
. What is alternative syntax.I tried to access this class library method from web application and it works fine.
Please suggest solution.
-
DotnetSparrow almost 13 yearsI dont need the assembly path rather I need file path. actually I need the alternative of this: HttpContext.Current.Server.MapPath("~/TestDevice/Data.xml")
-
The Evil Greebo almost 13 yearsSo what you're saying is you want the service to know the location of a data file located under a web application. Problem with that is the web application could get moved. If you want both a service and a web application to be able to have access to the same location then you might want to define that path location in a config file for each application, both pointing to the same place, and store your data in that location instead of under the web site's folder tree.