httpcontext.current.server.mappath对象引用未设置为对象的实例

soa*_*ing 36 c# nullreferenceexception

我在一个类中使用以下代码:

string filePath = HttpContext.Current.Server.MapPath("~/email/teste.html");
Run Code Online (Sandbox Code Playgroud)

文件teste.html位于文件夹中

但是当它打开文件时,会生成以下错误:

你调用的对象是空的.

nic*_*ine 76

不要使用Server.MapPath.这很慢.请改用它HttpRuntime.AppDomainAppPath.只要您的网站正在运行,您就可以使用此属性.

然后像这样使用它:

string filePath = Path.Combine(HttpRuntime.AppDomainAppPath, "email/teste.html");
Run Code Online (Sandbox Code Playgroud)


Yah*_*hia 7

如果代码没有从内的线程正在执行运行httprequestHttpContext.Currentnull(例如,当你的方法是通过所谓的BeginInvoke) -见http://forums.asp.net/t/1131004.aspx/1.

您可以随时使用HttpRuntimehttp://msdn.microsoft.com/en-us/library/system.web.httpruntime.aspx


The*_*acy 5

如果没有HttpContext(例如BeginInvoke,如Yahia所指出的通过调用方法),则对to的调用HttpContext.Current.Server.MapPath()必须失败。对于那些情况,HostingEnvironment.MapPath()System.Web.Hosting名称空间中。

string filePath = HostingEnvironment.MapPath("~/email/teste.html");
Run Code Online (Sandbox Code Playgroud)