Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?

like image 741
John Adams Avatar asked Jan 20 '11 00:01

John Adams


People also ask

What is the use of server MapPath in asp net?

The MapPath method maps the specified relative or virtual path to the corresponding physical directory on the server.

What is Server MapPath in MVC?

For example, Server. MapPath() allows a path of "files/file1. doc". It uses the current context to determine the path of the current page, for example, and then creates the relative path from there.

What is Server MapPath returns?

MapPath("/") returns C:\Inetpub\wwwroot. Server.


2 Answers

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

like image 138
Chtiwi Malek Avatar answered Sep 20 '22 15:09

Chtiwi Malek


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 ~/

like image 31
Hawxby Avatar answered Sep 23 '22 15:09

Hawxby