Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Absolute URL from base + relative URL in C#

Tags:

c#

.net

url

path

I have a base URL :

http://my.server.com/folder/directory/sample 

And a relative one :

../../other/path 

How to get the absolute URL from this ? It's pretty straighforward using string manipulation, but I would like to do this in a secure way, using the Uri class or something similar.

It's for a standard a C# app, not an ASP.NET one.

like image 601
Romain Verdier Avatar asked Sep 24 '08 18:09

Romain Verdier


People also ask

What is absolute URL and relative URL?

An absolute URL contains all the information necessary to locate a resource. A relative URL locates a resource using an absolute URL as a starting point. In effect, the "complete URL" of the target is specified by concatenating the absolute and relative URLs.

How do you make an absolute URL?

If you prefix the URL with // it will be treated as an absolute one. For example: <a href="//google.com">Google</a> . Keep in mind this will use the same protocol the page is being served with (e.g. if your page's URL is https://path/to/page the resulting URL will be https://google.com ).

How do you know if a URL is relative or absolute?

Original Answer. This will recognize an absolute URL, if: URL contains "://" anywhere after the first character, or. URL starts with "//" (protocol relative)


1 Answers

var baseUri = new Uri("http://my.server.com/folder/directory/sample"); var absoluteUri = new Uri(baseUri,"../../other/path"); 

OR

Uri uri; if ( Uri.TryCreate("http://base/","../relative", out uri) ) doSomething(uri); 
like image 124
Mark Cidade Avatar answered Sep 26 '22 00:09

Mark Cidade