当HTTPContext .Current为Nothing时,如何使用Server.MapPath

时间:2011-01-20 00:19:29

标签: asp.net vb.net httpcontext server.mappath

当我需要从Web服务器上的目录中删除一些图像文件时,我有一些代码可以正常工作:

Dim ImageURL As String = dsImages.Tables(0).Rows(iImgRow).Item("ImageURL")
Dim physicalName = Server.MapPath(ImageURL)
oUpload.DeleteFileFromServer(physicalName, iAdid, iImgID)

..但是当设置间隔在单独的线程中运行的维护任务确定需要删除上述文件时,我遇到了问题:

Dim ImageURL As String = dsImage.Tables(0).Rows(i - 1).Item("ImageURL")
Dim iImgID As Integer = dsImage.Tables(0).Rows(i - 1).Item("ImageId")
Dim physicalName As String = HttpContext.Current.Server.MapPath(ImageURL)
oUpload.DeleteFileFromServer(physicalName, iAdID, iImgID)

在后一种情况下, HttpContext.Current.Server.MapPath(ImageURL)的值为Nothing。

有没有办法获得此案例的完整路径?

2 个答案:

答案 0 :(得分:25)

当代码在线程内运行时, HttpContext.Current 不可用。

要获得您的Web应用程序路径,您可以使用:

System.Web.Hosting.HostingEnvironment.MapPath("~/")

或者您只需在 HttpRuntime.AppDomainAppPath 属性中找到它(推荐/更快)。

答案 1 :(得分:0)

假设路径是相对的,那么单独的进程不知道它们相对于哪个Web应用程序。在这种情况下,您需要将它存储在配置中,并将两者连接在一起或在〜/

上执行字符串替换
相关问题