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 lib开发者_C百科rary method from web application and it works fine.
Please suggest solution.
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..
This method works much better:
string baseDirectory = AppDomain.CurrentDomain.BaseDirectory;
It could be that when you are using windows service, you are no longer running a web app, therefore HttpContext and web server is not available. Try using System.IO.File for mapping, see whether that takes you to the correct directory.
Edit
private String yourFullPath = System.IO.Path.GetFullPath("/YourDirectory") + @"\";
精彩评论