提问人:soamazing 提问时间:7/28/2011 最后编辑:BangEqualsDestructorsoamazing 更新时间:6/26/2020 访问量:63539
httpcontext.current.server.mappath 对象引用未设置为对象的实例
httpcontext.current.server.mappath Object reference not set to an instance of an object
问:
我在类中使用以下代码:
string filePath = HttpContext.Current.Server.MapPath("~/email/teste.html");
文件 teste.html 位于文件夹中
但是,当它打开文件时,会生成以下错误:
对象引用未设置为对象的实例。
答:
不要使用 Server.MapPath。它很慢。请改用它。只要您的网站正在运行,您就始终可以使用此属性。HttpRuntime.AppDomainAppPath
然后像这样使用它:
string filePath = Path.Combine(HttpRuntime.AppDomainAppPath, "email/teste.html");
评论
如果代码不是从线程中运行的,则执行 then is(例如,当您的方法通过 调用时 ) - 请参阅 http://forums.asp.net/t/1131004.aspx/1 。httprequest
HttpContext.Current
null
BeginInvoke
您可以随时使用 see http://msdn.microsoft.com/en-us/library/system.web.httpruntime.aspxHttpRuntime
如果没有(例如,当通过 调用方法时,正如 Yahia 指出的那样),调用 必须失败。对于这些方案,命名空间中有。HttpContext
BeginInvoke
HttpContext.Current.Server.MapPath()
HostingEnvironment.MapPath()
System.Web.Hosting
string filePath = HostingEnvironment.MapPath("~/email/teste.html");
评论
../images/
问题:我在类库项目中有一个“Images”文件夹。但是使用上面的答案,我无法获取文件夹的物理路径来读取/写入该文件夹中的文件。
解决方案:下面的代码对我有用,可以在类库项目中获取物理路径。
string physicalPath = System.IO.Path.GetFullPath("..\\..\\Images");
我希望,它能帮助那些与我面临相同问题的人。
您可以使用类似于以下代码段的内容。需要注意的一件事是,我遇到了一个问题,我试图从TestMethod中访问.txt文件,但除此之外一切都失败了......是的,它也适用于非单元测试场景。
string filePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory,@"..\..") + "\\email\\teste.html";
评论
MapPath
NullReferenceException