How do you convert a url to a virtual path in asp.net without manual string parsing?

Kilhoffer picture Kilhoffer · Jan 29, 2009 · Viewed 10.1k times · Source

I've seen similar questions and answers regarding conversions from virtual to absolute and url, but how can I convert a url to a virtual path without manual string parsing?

Example:

I want "http://myserver/home.aspx" converted to: "~/home.aspx"

I realize the above example would be an easy string parsing routine, but I'm looking for a proper solution that will scale to the changing of the url format.

Answer

Daniel Schaffer picture Daniel Schaffer · Jan 29, 2009

You can get most of it from the Uri class:

new Uri("http://myserver.com/home.aspx").AbsolutePath

Then you just have to prepend the ~

Though, that will might break if you host in a subdirectory - I don't think there's a way to do it specifically in the context of the application you're running.

EDIT: This might do it:

VirtualPathUtility.ToAppRelative(new Uri("http://myserver.com/home.aspx").AbsolutePath);