How to convert url to virtual path in asp.net without manually parsing strings?

I saw similar questions and answers regarding conversions from virtual to absolute and url, but how can I convert a URL to a virtual path without manually parsing the strings?

Example:

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

I understand that the above example would be a simple procedure for parsing strings, but I am looking for a suitable solution that will scale to change the format of the URL.

+6
url path
source share
2 answers

You can get most of this lesson from the Uri class:

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

Then you just need to add ~

Although, this may break if you place it in a subdirectory - I do not think there is a way to do this specifically in the context of the application in which you are working.

EDIT: This can do it:

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

VirtualPathUtility.ToAppRelative Method (String) looks like what you're 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 to the ToAppRelative method, the resulting relative path of the application is "~ / sub / default.aspx".

+3
source share

All Articles