How to use Server.MapPath when HTTPContext .Current is Nothing

白昼怎懂夜的黑 提交于 2019-12-06 17:24:54

问题


I have some code that works fine when I need to delete some image files from a directory on my web server:

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

..but I am running into a problem when a maintenance task running in a separate thread at set intervals determines that files like the above need to be deleted:

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)

In this latter case, HttpContext.Current.Server.MapPath(ImageURL) has a value of Nothing.

Is there a way to get the full path for this case?


回答1:


Assuming that the paths are relative then the separate process does not know what they are relative to, which web application. In this case you will need to store it in the config and either append the two together or perform a string replace on ~/




回答2:


The HttpContext.Current is not available when your code is running inside a thread.

To have your web application path you can either use :

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

or you can simply find it in the HttpRuntime.AppDomainAppPath property (recommended/faster).



来源:https://stackoverflow.com/questions/4742257/how-to-use-server-mappath-when-httpcontext-current-is-nothing

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!