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

21

我有一些代码可以在需要从我的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

有没有一种方式可以获取这种情况下的完整路径?


可能是如何从global.asax中使用Server.MapPath()?的重复问题。 - Serj-Tm
2个回答

44

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

要获取您的Web应用程序路径,您可以使用以下方法之一:

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

或者你可以简单地在HttpRuntime.AppDomainAppPath属性中找到它(建议/更快)。


6
为什么推荐使用 HttpRuntime.AppDomainAppPath?它之所以更快,是因为“需要编写的代码更少”还是因为执行该语句更快?这种差异是否足够大,可以超越自己拼接路径的方便性呢? - El Mac

2
假设路径是相对的,那么独立进程不知道它们相对于哪个Web应用程序。在这种情况下,您需要将其存储在配置文件中,然后将两者连接在一起或对“~/”执行字符串替换。

8
我在https://dev59.com/SHNA5IYBdhLWcg3wgeEd 找到了更好的答案,但我不知道关闭这个问题的最佳方法。 - John Adams
很好,我学到了一些新东西。我想现在你可以让这个问题过去了。 - Hawxby

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接