Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Server.MapPath problems in Global.asa

0.00/5 (No votes)
7 Mar 2005 1  
Server.MapPath does NOT return the physical path of global.asa.

Introduction

The problem

Server.MapPath does not return the physical path of global.asa, but of the environment in which the first page of the application was loaded. For example:

Given the following directory tree,

c:\inetpub\wwwroot\global.asa
c:\inetpub\wwwroot\globaltable.txt
c:\inetpub\wwwroot\default.asp
c:\inetpub\wwwroot\anotherdir\anotherpage.asp

and a global.asa with code like:

<object id="GlobalTable" progid="IISSample.LookupTable" runat="Server" 
scope="Application"></object>
<script language="VBScript" runat="Server">

Sub Application_OnStart()
GlobalTable.LoadValues Server.MapPath("globaltable.txt"), 0
...

Server.MapPath in global.asa will return either "c:\inetpub\wwwroot\globaltable.txt" or "c:\inetpub\wwwroot\anotherdir\globaltable.txt" depending upon which page was loaded first "\default.asp" or "anotherdir\anotherpage.asp".

There are at least three situations in which this scenario could be possible:

  1. User went directly to http://www.yourcompany.com/anotherdir/anotherpage.asp by either saving the page to favorites or typing in the address field.
  2. User clicked on a link after a session time out.
  3. The application was restarted via either a IIS restart or a change in global.asa

The solution

Actually, there is no one solution (that I can think of), because it is all going to depend on other factors of every specific environment. So I will just list a couple of solutions based on some scenarios that I can think of.

The easy one - You know the relative virtual path in which your table resides and this does not change. For example, the scenario described above could be fixed by prefixing the name of the text file with a "\" and it will be treated as a full, virtual path.

But, there are cases in which you won't know this information, like if your application runs in two different environments on the same machine, or if you write templates that will be run on other environments over which you don't have any control, then you will have to resort to some other creative ways of fixing the path, like:

Sub Application_OnStart()
    Dim path, correctedPath    path = Server.MapPath( "." )
    correctedPath = path
    If UCase(Right( path, 11 )) = "\anotherdir" Then
       correctedPath = Left( path, Len( path ) - 11 )
End if
GlobalTable.LoadValues correctedPath & "\globaltable.txt", 0

Well, I hope this helps take out the mystery of some "why was my table not loaded" questions.

Felilpe Polo-Wood

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here