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

2

6

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.

Inflexible answered 29/1, 2009 at 21:43 Comment(0)
M
8

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);
Molest answered 29/1, 2009 at 21:51 Comment(3)
This won't work if the application runs in a subfolder, for example //myserver.com/myApp/home.aspx, as you have mentioned.Shirtmaker
@EDIT: that's what I've written i the comments for my post - so we have eventually put the solution together :-)Shirtmaker
Awesome, thanks, Daniel. I hadnt even looked at VirtualPathUtility. Works exactly the way I needed it to!Inflexible
S
3

VirtualPathUtility.ToAppRelative Method (String) seems to be what you are looking for (http://msdn.microsoft.com/en-us/library/ms150163.aspx)

If the virtual path for the application is "myapp" and the virtual path "/myApp/sub/default.asp" is passed into the ToAppRelative method, the resulting application-relative path is "~/sub/default.aspx".

Shirtmaker answered 29/1, 2009 at 21:52 Comment(1)
Hm, so that's only half the way. :-( Could you use the trick with Uri to make the path "virtual" and then call ToAppelative()? But I am afraid that there might be still situations when this doesn't work.Shirtmaker

© 2022 - 2024 — McMap. All rights reserved.