HttpContext.Current.Server null

Dot*_*row 5 asp.net windows-services asp.net-mvc-2

我有一个Windows服务,它使用类库中的方法与相同的asp.net解决方案.在类库中,我有一个方法如下:

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

当控制来到这条线.我得到例外.我试图调试代码,发现当服务尝试访问此方法时,HttpContext.Current.Server就是null.什么是替代语法.

我试图从Web应用程序访问此类库方法,它工作正常.

请建议解决方案.

The*_*ebo 5

HttpContext.Current返回null,因为您的Windows服务未在IIS或其他某些Web服务器提供程序下运行.

但是,您可以使用反射找到服务的执行路径:

System.Reflection.Assembly.GetExecutingAssembly().Location
Run Code Online (Sandbox Code Playgroud)

^应该返回执行服务的路径..

  • 我不需要汇编路径,而我需要文件路径。实际上,我需要以下替代方法:HttpContext.Current.Server.MapPath(“〜/ TestDevice / Data.xml”) (2认同)