Monday, July 31, 2006

Resolving links from the application root

One of the things that I've got used to taking for granted is the ability to use the tilde (~) to specify the application root when specifying a link, in a HyperLink control, for example. Having recently ventured into the realm of writing my own controls I need to parse links like this for myself.

A quick Google later and it looks like the Control.ResolveUrl() method is the way to go, although as an aside, there appears to be a new Control.ResolveClientUrl() method in 2.0 as well. The docs don't really go out of their way to explain the difference as far as I can tell, but from my own tests it would appear that the former will provide an absolute path (using the TemplateSourceDirectory property according to the docs), whereas the latter will give you a relative path.

Quick example:
From a page at /WebApp/dir/page.aspx that wants to create a link to "~/otherdir/link.html":

ResolveUrl() gives: /WebApp/otherdir/link.html
ResolveClientUrl() gives: ../otherdir/link.html