How to use app-relative paths in ASP.NET – level 100

I’ve been using this feature since the beginning, but I’ve come to realize
that a lot of people aren’t aware of this.  The application path shortcut:

When including any resource in your page whether it be a user control,
image, css or whatever, it has to be located.  The simplest thing to do is
to type the entire path, http://localhost/myApp/myStyle.css, but that isn’t
very maintainable because when you deploy, you have to change this
reference.  So the next step is making the path relative to the page (buried
2 levels deep):  ../../myStyle.css, but what if the site structure changes?
What do you do?  You could make it domain-relative:  /myApp/myStyle.css, but
what if your application needs to be deployed to it’s own domain: ?  Now this reference is broken.  Some people get
around this by setting the path with Request.ApplicationPath +
“/myStyle.css”, but this doesn’t work in all cases.  If you have a virtual
path, you get /myApp, but if you are at the root, you get “/”, so in the
case of /myApp, you have to add a “/” to the end.

To get around all this, use “~/” as a shortcut to you application path.
With that shortcut at the beginning of your path, any server control will
resolve the url for you.  If you use this in a non-server control or just
print it out, you will need to resolve it yourself using the ResolveUrl(…)
method of the Control class.  This method is inherited by all controls, so
you can use it directly in Page, UserControl and all web controls.  I use
nothing but app-relative paths now.

In .Net 2.0, we’ll get more App-relative shortcut properties like
Request.AppRelativePath.  It’s really a much cleaner way to represent a
resource relative to the application no matter what the path to the
application is.