Get virtual path for a full path in asp classic

C. Ross picture C. Ross · May 20, 2009 · Viewed 22.6k times · Source

How can I get the virtual path for a full path in ASP classic. Note that the full path may be under a virtual directory and therefore the simplistic

virtPath = Replace(fullPath, Server.MapPath("/"), "") 

method will not work.

Edit: To clarify, an example follows

  • Full Windows File Path (known): \\MyServer\MyShare\Web\Site\Logs\Test.txt
  • My Website has a Virtual directory called Logs that Points to \\MyServer\MyShare\Web\Site\Logs\.
  • Virtual Path (unknown): /Logs/Text.txt
  • Http path (unknown, needed): http://Site/Logs/Test.txt
  • The code is in a asp page in the main app, not under any virtual directories. It is located on a separate server from the file in question.
  • IIS 6.0

    How do I find the virtual path from the full file path?

Answer

shovavnik picture shovavnik · Jun 3, 2010

In case anyone's interested, Anthony Jones' answer showed me the way to getting the application's relative root consistently. So if you have a site at http://example.com and a local development equivalent at http://localhost/example, you can find your root with this function:

Function ToRootedVirtual(relativePath)
    Dim applicationMetaPath : applicationMetaPath = Request.ServerVariables("APPL_MD_PATH")
    Dim instanceMetaPath : instanceMetaPath = Request.ServerVariables("INSTANCE_META_PATH")
    Dim rootPath : rootPath = Mid(applicationMetaPath, Len(instanceMetaPath) + Len("/ROOT/"))
    ToRootedVirtual = rootPath + relativePath
End Function

You can then call it like this to get the root path:

ToRootedVirtual("/")

Which will return:

  • / on example.com
  • /example/ on localhost/example

You can also use it without the slash:

ToRootedVirtual("")