18

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?

John Adams
  • 4,573
  • 23
  • 85
  • 124
  • Possible duplicate of [How can I use Server.MapPath() from global.asax?](http://stackoverflow.com/questions/935940/how-can-i-use-server-mappath-from-global-asax) – Serj-Tm Oct 15 '15 at 17:20

2 Answers2

36

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).

Chtiwi Malek
  • 9,757
  • 1
  • 66
  • 65
  • 4
    Why is `HttpRuntime.AppDomainAppPath` recommended/faster? Is it faster in terms of "less code to write"? Or is it faster when running the statement? Is the difference big enough to beat the convenience of not having to concatenate the paths by myself? – El Mac May 11 '18 at 14:29
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 ~/

Hawxby
  • 2,648
  • 17
  • 29
  • 8
    Found a better answer at: http://stackoverflow.com/questions/935940/how-can-i-use-server-mappath-from-global-asax - but I don't know the best way to close this question. – John Adams Jan 20 '11 at 16:28
  • Nice, learnt something new there. I think you just leave the question to die now. – Hawxby Jan 20 '11 at 16:56