【问题标题】:How to use Server.MapPath when HTTPContext .Current is Nothing当 HTTPContext .Current 为 Nothing 时如何使用 Server.MapPath
【发布时间】:2011-06-12 03:38:39
【问题描述】:

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

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。

有没有办法获得这种情况的完整路径?

【问题讨论】:

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


【解决方案1】:

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

要拥有您的网络应用程序路径,您可以使用:

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

或者您可以简单地在 HttpRuntime.AppDomainAppPath 属性中找到它(推荐/更快)。

【讨论】:

  • 为什么推荐/更快HttpRuntime.AppDomainAppPath?就“编写更少的代码”而言,它更快吗?还是运行语句时更快?差异是否足以超越不必自己连接路径的便利?
【解决方案2】:

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

上执行字符串替换

【讨论】:

  • stackoverflow.com/questions/935940/… 找到了更好的答案 - 但我不知道结束这个问题的最佳方法。
  • 很好,在那里学到了一些新东西。我想你现在就让这个问题去死吧。
猜你喜欢
  • 1970-01-01
  • 2015-04-15
  • 1970-01-01
  • 1970-01-01
  • 2019-01-12
  • 1970-01-01
  • 2010-09-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多