Blog Stats
  • Posts - 4
  • Articles - 0
  • Comments - 17
  • Trackbacks - 5

 

Reverse Server.MapPath()

Here's a simple ASP.NET function that will get the opposite result of the Server.MapPath() function.  This comes in handy when you're retrieving files recently saved by your web application.  Pass it a fully qualified path and it returns a URL

Public Function MapURL(ByVal Path As String) As String
     Dim AppPath As String = _
    
HttpContext.Current.Server.MapPath("~")
     Dim url As String = String.Format("~{0}" _
     
, Path.Replace(AppPath, "").Replace("\", "/"))
     Return url
End Function

Of course, you will have to make sure that the path is valid and the file is under the virtual root.

Enjoy!


Feedback

# re: Reverse Server.MapPath()

Gravatar Ah, very handy. Good thinking. Bless my fileinfos. :) 8/19/2006 9:10 AM | Rabid

# re: Reverse Server.MapPath()

Gravatar Hi..

I was searching for this.. and it is amazing.. Thanks a lot!! Ur post is valuable. 9/12/2006 5:06 AM | Dunlop

# re: Reverse Server.MapPath()

Gravatar Please convert "?" to "/"
and convert "=" to "/" 3/26/2007 12:09 AM | vignesh

# re: Reverse Server.MapPath()

Gravatar any chance to make it in JScript?
I have a full application done that way, and need this in JScript.

Thanks in advance 3/27/2007 3:15 PM | Lord Vader

# re: Reverse Server.MapPath()

Gravatar When using your script, I found that it didn't work when the application is running in a directory below the root of the URL. I changed the setting of the url variable to use the following code:

string url = String.Format("{0}" , HttpContext.Current.Request.ApplicationPath + path.Replace(AppPath, "").Replace("\\", "/"));

This just inserts the path of the application on the server before putting in the path of the image relative to the application.
7/13/2007 3:42 PM | Eric Steuart

# re: Reverse Server.MapPath()

Gravatar very cool little trick..thanks!! 10/31/2007 5:08 PM | Punit

# re: Reverse Server.MapPath()

Gravatar I ran into a minor snag with this. I'd used directory.getfiles to get my file list. This converted the path to lower-case. HttpContext.Current.Server.MapPath did not, so the replace statement didn't work. Setting path and apppath to .lower solves this. 10/29/2009 11:51 AM | Jeff Flanagan

# re: Reverse Server.MapPath()

Gravatar This works great until you have a virtual directory in your application. Then, the physical directory of the root app path is not always the same as physical directories of the virtual folder. Any Suggestions???

This is very good though in most circumstances. 10/30/2009 1:07 PM | Chris Francis

Post a comment





 

 

 

Copyright © Albert Raiani